Depth of the child in the DOM

Is there any way to find out what is the depth of the child based on the 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" (starting at 0). Knowing that "li" are on the same level.

thanks

+3
source share
3 answers

Assuming you want to find the depth of the child in relation to an 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")

The complete solution will have to handle the case where the specified parent is not the ancestor of the descendant.

Alternatively, and only if you support ES5 and higher, working with DOM nodes directly can eliminate jQuery dependency:

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'))
+6
source
$.fn.depth = function() {
  return $(this).parents().length;
};

or something like that.

+8
source

, - : ( , , .)

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, closest().

0

Source: https://habr.com/ru/post/1720588/


All Articles