JavaScript 遍历DOM树

来源:互联网 发布:c语言常用算法 编辑:程序博客网 时间:2024/05/25 13:33

1. 前序遍历

function preOrder(node){    if(node){        arr.push(node);        preOrder(node.firstElementChild);        preOrder(node.lastElementChild);    }}

2. 中序遍历

function inOrder(node){    if(node){        inOrder(node.firstElementChild);        arr.push(node);        inOrder(node.lastElementChild);    }}

3. 后序遍历

function postOrder(node){    if(node){        postOrder(node.firstElementChild);        postOrder(node.lastElementChild);        arr.push(node);    }}

4. 广度优先遍历

// 递归版本function bfs(root){    const nodes = Array.isArray(root) ? root : [root];    const nextNodes = [];    // 广度优先    nodes.forEach(node => {        if (node.children && node.children.length) {            Array.prototype.slice.call(node.children).forEach(ele => {                console.log(ele.className);                nextNodes.push(ele);            });        }    });    if (nextNodes.length) {        bfs(nextNodes);    }}// 非递归版本function bfs(root) { // 传参为根节点    let nodes = Array.prototype.slice.call(root.children);    while(nodes.length) {        let tmp = [];        nodes.forEach(function (node) {            console.log(node.className);            if (node.children.length) {                tmp = tmp.concat(Array.prototype.slice.call(node.children));            }        });        nodes = tmp.slice(0);    }}

5. 深度优先遍历

function dfs(root) {    console.log(root.className);    const nodes = Array.prototype.slice.call(root.children);    if (nodes.length) {        nodes.forEach(function (node) {            dfs(node);        });    }}
0 0
原创粉丝点击