Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get maximum depth of selected node in DOM using jQuery

Tags:

jquery

dom

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.

like image 247
Primoz Rome Avatar asked Sep 11 '12 12:09

Primoz Rome


1 Answers

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
like image 111
Šime Vidas Avatar answered Oct 13 '22 22:10

Šime Vidas