如何从具有特定类的HTML树中找到最深的元素?

时间:2013-05-30 08:39:01

标签: javascript jquery html

我有一个菜单。打开树时,它将获得类active。我不想使用课程active获得菜单中最深的子菜单。

2 个答案:

答案 0 :(得分:1)

您可以使用parents()集合计算元素的深度,然后返回特定选择器的最低值。试试这个:

<div>
    1
    <div class="active">1.1</div>
    <div class="active">
        1.2
        <div class="active">
            1.2.1
            <div class="active">1.2.1.1</div>            
        </div>
        <div class="active">1.2.2</div>
    </div>
    <div class="active">1.3</div>
    <div class="active">
        1.4
        <div class="active">1.4.1</div>
        <div class="active">1.4.2</div>
    </div>
    <div class="active">1.5</div>
</div>
var $elems = $('.active'), $deepest, lowestLevel = 0;
$elems.each(function() {
    var depth = $(this).parents().length;
    if (depth > lowestLevel) {
        $deepest = $(this);
        lowestLevel = depth;
    }
});
$deepest.css('border', '1px solid #C00');

Example fiddle

答案 1 :(得分:0)

还有香草版:

function deepest (subMenu, select) { 
  return [].slice.call (subMenu.querySelectorAll (select)).reduce (
    function (deepest, el) {
      for (var d = 0, e = el; e !== subMenu; d++, e = e.parentNode);
      return d > deepest.d ? {d: d, el: el} : deepest;
    }, {d: 0, el: subMenu}).el;
 };

打电话
deepest (subMenu, '.active');

其中第二个参数选择要考虑的元素。

@Rory's fiddle

的修改版本上测试过