This article will share the DOM node tree depth traversal, breadth traversal code.

Suppose I just iterate over the body and its structure looks like this:

Output: [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]; // Filter text node, script node 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) traverses all siblings of the parent node and traverses its children.

Output: [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]; // Filter text nodes, script nodes 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)); Copy code 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]; // Filter text nodes, script nodes 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));