depth of a child in the DOM

江枫思渺然 提交于 2021-01-27 14:51:38

问题


Can I have any way to know which is the depth of a child based on a container. Example:

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

You should get 2 for "xelement" (taking as starting at 0). Knowing that the "li" are at the same level.

Thanks


回答1:


Assuming you want to find the depth of a child in reference to some arbitrary ancestor.

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")

A complete solution will need to handle the case where the specified parent isn't an ancestor of descendant.

Alternatively, and only if you support ES5 and above, working directly with DOM nodes can eliminate the dependency on 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:


$.fn.depth = function() {
  return $(this).parents().length;
};

or something like that.




回答3:


A simple recursive function, something along the lines of: (While I do recommend using a toolkit, this is a good little learning game, bugs fixing left as an exercise for the readers.)

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)

Edit: If you are using jQuery, see the closest() function.



来源:https://stackoverflow.com/questions/1596365/depth-of-a-child-in-the-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!