andres descalzo
andres descalzo

Reputation: 14967

depth of a child in the DOM

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

Upvotes: 3

Views: 4913

Answers (3)

user166390
user166390

Reputation:

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.

Upvotes: 0

cletus
cletus

Reputation: 625077

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

Upvotes: 6

Pointy
Pointy

Reputation: 413709

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

or something like that.

Upvotes: 8

Related Questions