js手动实现getelementbyid
手动实现 getElementById 的方法
递归遍历 DOM 树
通过递归遍历 DOM 树的每个节点,检查节点的 id 属性是否匹配目标值。如果找到匹配的节点,立即返回该节点;否则继续遍历子节点。

function getElementById(root, id) {
if (root.id === id) {
return root;
}
for (let child of root.children) {
const found = getElementById(child, id);
if (found) {
return found;
}
}
return null;
}
使用 BFS(广度优先搜索)
采用队列实现广度优先搜索,逐层遍历 DOM 树,直到找到目标节点。

function getElementById(root, id) {
const queue = [root];
while (queue.length > 0) {
const node = queue.shift();
if (node.id === id) {
return node;
}
for (let child of node.children) {
queue.push(child);
}
}
return null;
}
使用 DFS(深度优先搜索)的非递归实现
通过栈实现深度优先搜索的非递归版本,避免递归可能导致的堆栈溢出问题。
function getElementById(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;
}
注意事项
- 性能考虑:递归实现可能在 DOM 树很深时导致堆栈溢出,非递归的 BFS 或 DFS 更安全。
- 兼容性:手动实现通常用于理解原理,实际开发中应优先使用原生
document.getElementById。 - 扩展性:可以进一步优化算法,例如支持动态加载的 DOM 节点。
示例调用
const rootElement = document.documentElement;
const targetElement = getElementById(rootElement, 'myId');
console.log(targetElement);






