js手动实现getelementbyid
实现思路
手动实现 getElementById 需要遍历 DOM 树,检查每个节点的 id 属性是否与目标匹配。递归或迭代方式均可实现,但需注意性能优化。
递归实现
递归方法深度优先遍历 DOM,找到第一个匹配的节点后立即返回。
function getElementByIdRecursive(node, id) {
if (!node) return null;
if (node.id === id) return node;
for (const child of node.children) {
const found = getElementByIdRecursive(child, id);
if (found) return found;
}
return null;
}
迭代实现(广度优先)
使用队列实现广度优先搜索,适合层级较深的 DOM 结构。
function getElementByIdIterative(root, id) {
const queue = [root];
while (queue.length > 0) {
const node = queue.shift();
if (node.id === id) return node;
queue.push(...node.children);
}
return null;
}
性能优化建议
- 提前终止:找到目标后立即停止遍历。
- 避免递归爆栈:对超深 DOM 树使用迭代方式。
- 缩小搜索范围:若已知大致区域,可从特定子树开始搜索。
使用示例
// 从 document.body 开始搜索
const element = getElementByIdRecursive(document.body, 'targetId');
console.log(element);
注意事项
- 原生
getElementById由浏览器引擎优化,性能远高于手动实现。 - 手动实现仅适用于理解原理或特殊场景(如虚拟 DOM 操作)。







