I would like to count count maximum 'depth' of the DOM tree structure (the length of the longest branch of a tree given its root). For example:
<div class="group level0" id="group1">
<div class="group level1" id="group2">
<div class="group level2" id="group3">
<div class="group level3">
</div>
</div>
</div>
<div class="group level1">
<div class="group level2">
</div>
</div>
</div>
For example result for div#group1
would be 3. Result for div#group2
would be 2 and result for div#group3
would be 1.
Here:
var calcDepth = function ( root ) {
var $children = $( root ).children();
var depth = 0;
while ( $children.length > 0 ) {
$children = $children.children();
depth += 1;
}
return depth;
};
Live demo: http://jsfiddle.net/WqXy9/
calcDepth( $('#group1')[0] ) // => 3
calcDepth( $('#group2')[0] ) // => 2
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