How to find the maximum depth of the DOM tree using native js?
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)
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);
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)
ScreenShot