depth of a child in the DOM

javascript, jquery

Solution

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

Problem

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

Original source