js手动实现getelementbyid
手动实现 getElementById
在 JavaScript 中,可以通过递归或迭代的方式手动实现 getElementById 的功能。以下是两种常见的实现方法:
递归实现
递归方法会遍历 DOM 树的每个节点,检查其 id 是否匹配目标值。
function getElementByIdRecursive(node, id) {
if (!node) return null;
if (node.id === id) return node;
for (let child of node.children) {
const found = getElementByIdRecursive(child, id);
if (found) return found;
}
return null;
}
// 使用方式
const element = getElementByIdRecursive(document.body, 'targetId');
迭代实现
迭代方法使用队列(广度优先搜索)或栈(深度优先搜索)遍历 DOM 树。

function getElementByIdIterative(root, id) {
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
if (node.id === id) return node;
for (let i = node.children.length - 1; i >= 0; i--) {
stack.push(node.children[i]);
}
}
return null;
}
// 使用方式
const element = getElementByIdIterative(document.body, 'targetId');
注意事项
- 递归方法可能在深度较大的 DOM 树中导致栈溢出。
- 迭代方法通常更高效,适合大型 DOM 树。
- 原生
document.getElementById性能更高,手动实现主要用于学习目的。






