1. 程式人生 > >js深度、廣度 遍歷 dom樹

js深度、廣度 遍歷 dom樹


// 深度遍歷
function interator(node) {
    console.log(node);
    if (node.children.length) {
        for (var i = 0; i < node.children.length; i++) {
            interator(node.children[i]);
        }
    }
}

// 廣度遍歷
function interator(node) {

    var arr = [];
    arr.push(node);
    while (arr.length
> 0) { node = arr.shift(); console.log(node); if (node.children.length) { for (var i = 0; i < node.children.length; i++) { arr.push(node.children[i]); } } } }