我想计算DOM树结构的最大'深度'(给定其根的树的最长分支的长度)。例如:
<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>
例如,div#group1
的结果为3. div#group2
的结果为2,div#group3
的结果为1。
答案 0 :(得分:6)
下面:
var calcDepth = function ( root ) {
var $children = $( root ).children();
var depth = 0;
while ( $children.length > 0 ) {
$children = $children.children();
depth += 1;
}
return depth;
};
现场演示: http://jsfiddle.net/WqXy9/
calcDepth( $('#group1')[0] ) // => 3
calcDepth( $('#group2')[0] ) // => 2
答案 1 :(得分:1)
此函数将通过给定root
的DOM树找到最大深度,仅通过具有特定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);
这是一个带有稍微复杂的DOM的演示:
答案 2 :(得分:0)
这是非递归解决方案:
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;
}
答案 3 :(得分: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;
}
};