5

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.

4

4 回答 4

6

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
于 2012-09-11T13:05:54.460 回答
1

This function will find the maximum depth through the DOM tree from a given root, tracing the tree only through nodes with a specific class:

function getDepth(root, className) {
    var children = root.children('.' + className),
        maxDepth = 0;

    if (children.length === 0) {
        return maxDepth;
    } else {
        children.each(function() {
            var depth = 1 + getDepth($(this), className);
            if (depth > maxDepth) {
                maxDepth = depth;
            }
        });
    }

    return maxDepth;
}

var root = $('#group1');
var className = 'group';

var depth = getDepth(root,className);​

Here's a demo with a slightly more complex DOM:

--- jsFiddle DEMO ---

于 2012-09-11T13:09:13.937 回答
0

Here is non recursive solution:

function len(sel) {
    var depth = 0;
    $(sel + " :not(:has(*))").each(function() {
        var tmp = $(this).parentsUntil(sel).length + 1;
        if (tmp > depth) depth = tmp;
    });
    return depth;
}

DEMO: http://jsfiddle.net/f2REj/

于 2012-09-11T13:26:16.253 回答
0
jQuery.fn.depth = function() {
    var children = jQuery(this).children();
    if (children.length === 0)
        return 0;
    else
    {
        var maxLength = 0;
        children.each(function()
        {
            maxLength = Math.max(jQuery(this).depth(), maxLength);
        });
        return 1 + maxLength;
    }
};

Demo: http://jsfiddle.net/7Q3a9/

于 2012-09-11T13:50:03.963 回答