分享 DOM 節點樹深度遍歷、廣度遍歷代碼。html
假定我僅遍歷 body 且其結構以下:node
<body> <section class="container"> <div class="left"> <div class="menu"></div> </div> <div class="right"> <div class="box1"></div> <div class="box2"></div> </div> </section> </body>
遍歷完父節點的全部子節點的子節點的子節點...再遍歷其兄弟節點。git
輸出:[section.container, div.left, div.menu, div.right, div.box1, div.box2]github
const DFS = { nodes: [], do (root) { for (let i = 0;i < root.childNodes.length;i++) { var node = root.childNodes[i]; // 過濾 text 節點、script 節點 if ((node.nodeType != 3) && (node.nodeName != 'SCRIPT')) { this.nodes.push(node); this.do(node); } } return this.nodes; } } console.log(DFS.do(document.body));
遍歷完父節點的全部兄弟節點再遍歷其子節點。dom
輸出:[section.container, div.left, div.right, div.menu, div.box1, div.box2]this
const BFS = { nodes: [], do (roots) { var children = []; for (let i = 0;i < roots.length;i++) { var root = roots[i]; // 過濾 text 節點、script 節點 if ((root.nodeType != 3) && (root.nodeName != 'SCRIPT')) { if (root.childNodes.length) children.push(...root.childNodes); this.nodes.push(root); } } if (children.length) { var tmp = this.do(children); } else { return this.nodes; } return tmp; } } console.log(BFS.do(document.body.childNodes));
非遞歸版:code
const BFS = { nodes: [], do (roots) { var roots = new Array(...roots); for (let i = 0;i < roots.length;i++) { var root = roots[i]; // 過濾 text 節點、script 節點 if ((root.nodeType != 3) && (root.nodeName != 'SCRIPT')) { if (root.childNodes.length) roots.push(...root.childNodes); this.nodes.push(root); } } return this.nodes; } } console.log(BFS.do(document.body.childNodes));
做者:呆戀小喵htm
個人後花園:https://sunmengyuan.github.io...遞歸
個人 github:https://github.com/sunmengyuanip