api*_*nny 3 html javascript dom
例如:
// ...
<body>
<div>
<div>
</div>
</div>
</body>
// ...
Run Code Online (Sandbox Code Playgroud)
这个巢深度是3?但更一般地说,我如何遍历DOM以查找此信息?
我有兴趣将DOM视为一个模拟为对象文字的n-ary树,如本文所述:
优雅的递归解决方案
使用此功能 - height(document.body)
function height(el) {
if (!el.children)
return 0;
var max = -1;
for ( var i = 0; i < el.children.length; i++) {
var h = height(el.children[i]);
if (h > max) {
max = h;
}
}
return max + 1;
}
Run Code Online (Sandbox Code Playgroud)
function getMaximumDepth (element) {
var child = element.firstChild;
var childrenDepth = [];
if ( ! child ) {
return 1;
}
while (child) {
childrenDepth.push( getMaximumDepth(child) );
child = child.nextSibling;
}
return Math.max.apply(Math, childrenDepth) + 1;
}
Run Code Online (Sandbox Code Playgroud)
演示: http //jsfiddle.net/53R2p/
| 归档时间: |
|
| 查看次数: |
4660 次 |
| 最近记录: |