Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DOM hierarchy level of element (count descendant levels)

Is there an efficient way to count the deepest descendant level of a specific element?

Example:

<div id="wrapper">
  <ul>
    <li class="first">first</li>
    <li class="active">second</li>
    <li class="last"><a>third</a></li>
  </ul>
</div>

#wrapper should return a descendant level of 4 because the deepest chain goes like this: #wrapper > ul > li > a.

li.first should return 1 because it has no children and li.last should return 2 because of li.last > a.

I could do a $('#wrapper').find(*) and iterate through all results, which should be quite slow for elements that have lots of descendants, especially for the body element.

Here is a start for experimenting: http://jsbin.com/ixeWaja/1/edit

Any ideas how to efficiently solve this?

like image 605
Alp Avatar asked Aug 31 '13 18:08

Alp


People also ask

How do I grab an element from a dom?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object.

How do you check if an element is inside another element?

contains() method checks if an element is inside another, and returns a boolean: true if it is, and false if it's not. Call it on the parent element, and pass the element you want to check for in as an argument.

Which object is at the top of the hierarchy?

Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.


1 Answers

Efficiency is probably not going to be your greatest concern if you ultimately need the depth, but this is a pretty concise and efficient way to do it.

var el = $("#wrapper");
var i = 0;

while ((el = el.children()).length) {
    i++;
}

http://jsbin.com/ixeWaja/4/

like image 87
user2736012 Avatar answered Oct 13 '22 00:10

user2736012