DOM 的深度优先搜索,本质就是遍历一棵树:
- 先访问当前节点
- 再访问它的子节点
DOM 树天然就是树结构,所以很适合 DFS。
1. 递归版 DFS
这是最直接的写法。
function dfs(node) { if (!node) return; console.log(node); // 访问当前节点 const children = node.children; for (let i = 0; i < children.length; i++) { dfs(children[i]); } }使用:
dfs(document.body);2. 如果只想输出标签名
function dfs(node) { if (!node) return; console.log(node.tagName); const children = node.children; for (let i = 0; i < children.length; i++) { dfs(children[i]); } }3. 迭代版 DFS
如果面试官要求不能用递归,可以用栈来模拟。
写法
function dfs(root) { if (!root) return; const stack