This article will share DOM node tree traversal depth, breadth traversal code.
I just assumed that traverse the body and its structure is as follows:
<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>
Depth traversal (DFS)
Child child node of all child nodes of the parent node ... been traversed and then traverse its siblings.
输出:[section.container, div.left, div.menu, div.right, div.box1, div.box2]
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));
Breadth traversal (BFS)
All the siblings been traversed parent node re-iterate its child nodes.
输出:[section.container, div.left, div.right, div.menu, div.box1, div.box2]
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));
Non-recursive version:
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));
Original: stay small meow love https://www.jianshu.com/p/cef409b161ba