代码之家  ›  专栏  ›  技术社区  ›  andres descalzo

子级在DOM中的深度

  •  3
  • andres descalzo  · 技术社区  · 15 年前

    我能有任何方法知道哪个是基于容器的孩子的深度吗? 例子:

    <div id="dontainer">
       <ul>
          <li>1</li>
          <li>2</li>
          <li id="xelement">3</li>
          <li>4</li>
          <li>5</li>
       </ul>
    </div>
    

    “xelement”应该得到2(从0开始)。知道“li”在同一水平。

    谢谢

    3 回复  |  直到 8 年前
        1
  •  6
  •   Dane Macaulay cletus    8 年前

    假设你想找到某个任意祖先的子代的深度。

    function depth(parent, descendant) {
      var depth = 0;
      var el = $(descendant);
      var p = $(parent)[0];
      while (el[0] != p) {
        depth++;
        el = el.parent();
      }
      return depth;
    }
    
    // Example call:
    depth(".mainContent", "li")
    

    完整的解决方案需要处理指定的父代不是子代祖先的情况。

    或者,只有支持ES5和更高版本,直接使用DOM节点才能消除对jquery的依赖:

    function depth(parent, descendant) {
        var depth = 0;
        while (!descendant.isEqualNode(parent)) {
          depth++;
          descendant = descendant.parentElement;
        }
        return depth;
    }
    
    // Example call:
    depth(document.querySelector('.mainContent'), document.querySelector('li'))
    
        2
  •  8
  •   Pointy    15 年前
    $.fn.depth = function() {
      return $(this).parents().length;
    };
    

    或者类似的。

        3
  •  0
  •   user166390    15 年前

    一个简单的递归函数,类似于: (虽然我确实推荐使用工具包,但这是一个很好的小学习游戏,修复漏洞留给读者作为练习。)

    function countDepth(node, stopPredicate, count) {
      count = count || 0
      stopPredicate = stopPredicate || function () {}
      if (stopPredicate(node) || !node.parentNode) {
        return count
      }
      return countDepth(node.parentNode, stopPredicate, count + 1)
    }
    
    var depth = countDepth(document.getElementById("xelement"), function (node) {
      return "dontainer" == node.id
    })
    
    // or, with no predicate -- will count *full* depth
    // depth = countDepth(document.getElementById("xelement"))
    
    alert(depth)
    

    编辑:如果您使用jquery,请参见最接近的()函数。