javascript - Native js to find the maximum depth of the DOM tree
过去多啦不再A梦
过去多啦不再A梦 2017-07-05 11:07:52
0
2
1365

How to find the maximum depth of the DOM tree using native js?

过去多啦不再A梦
过去多啦不再A梦

reply all(2)
Ty80

Recursive implementation

I used the children attribute of the dom node to traverse and recurse

The recursive routine is: Return (1 + the maximum value of the depth of the child nodes)

// map(e => e + 1)([0, 1, 2]) 
// => 1, 2, 3 
// 类似于数组的map方法 不过这里柯里化了 
var map = cb => arr => Array.prototype.map.call(arr, cb); 

// 取数组最大值 
// max([0, 1, 2])
// => 2 
var max = arr => arr.reduce((acc, cur) => {
    if (cur >= acc) return cur; 
    else return acc; 
}, arr[0]); 

// 递归函数 
var nextChildren = node => {
    // 基准条件 
    if (node.children.length === 0) return 1; 
    else {
        // 求子节点们的长度 并取最大值 
        var deeps = map(nextChildren)(node.children); 
        
        return 1 + max(deeps); 
    }
}

// 计算 
var $body = document.getElementsByTagName('body')[0];
var deep = nextChildren($body); 
console.log(deep); 

ScreenShot

三叔
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template