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?
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.
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.
Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With