Home  >  Q&A  >  body text

javascript - Native js to find the maximum depth of the DOM tree

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

过去多啦不再A梦过去多啦不再A梦2662 days ago1318

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-07-05 11:09:52

    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

    reply
    1
  • 三叔

    三叔2017-07-05 11:09:52

    reply
    0
  • Cancelreply