views:

106

answers:

4

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

A: 

Are you asking how to find the depth of a child in a parent, given both? If so, it's as easy as iterating through all the child's parents until you hit the desired parent and keeping a count.

Thom Smith
+1  A: 
$.fn.depth = function() {
  return $(this).parents().length;
};

or something like that.

Pointy
oh wait - by "based on a container" you mean the depth relative to the container. Well, you could get the depth of both and subtract, or use a filter expression like "#containerId *" in the first call.
Pointy
For absolute depth in the tree I like this solution for jquery.<body> ends up being at depth == 1.
Scott Kirkwood
+1  A: 

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;
}

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

Of course this can be done with vanilla Javascript too, particularly if you specify that the arguments must be IDs.

cletus
We modify the example with "el[0]!=parent[0]" because ".not" removes the elements and we need to know if they are different.
andres descalzo
A: 
pst