我知道一些浏览器(今天大多数浏览器?)使用一个 ID 制作所有元素的哈希表。所以在这种情况下,对 document.getElementById() 的调用可以只搜索哈希表。但是在 DOM 树的上下文中它将如何执行此操作 - 例如,它是深度优先搜索吗?
我问这个问题是因为我想知道放置 DOM 元素的最快位置在哪里,所以它会在搜索本身开始时或接近搜索时立即在搜索中找到。
快速浏览了一下,找不到关于此主题的任何具体信息。
非常感谢任何帮助。
最佳答案
由于 DOM 实现依赖于浏览器,每个浏览器都可能以不同的方式实现它。浏览器也有可能拥有所有 ID 的 HashMap 并执行 document.getElementById
使用它。
为了了解浏览器在 DOM 中查找的顺序,您可以查看 document.all
包含 document
中所有 DOM 元素的普通列表的集合.对于 Chrome、Safari 和 Firefox,它似乎是 DFS。
另一个有趣的问题是:如果同一文档中的两个元素具有相同的 ID,document.getElementById
将返回哪个元素? .使用下面的代码片段可以看出,它是使用 DFS 算法找到的第一个元素(至少在下面提到的浏览器中是这样)。
HTML
<div>
<div id="id" data-index="DFS"></div>
</div>
<div id="id" data-index="BFS"></div>
JavaScript
console.log(document.getElementById('id').getAttribute('data-index'));
控制台输出
DFS
笨蛋
http://plnkr.co/edit/jaUolyxwrZcXsNXwkmtm?p=preview
编辑:
关于答案评论中的附加问题
I am not sure if the search will stop at the location of the first result, which would of course be quicker...is there a way to test this at all?
您可以在下面找到一个代码片段,它在另一个元素和一个同级元素中创建了 10000 个元素。在一种情况下,相同的 ID 设置为最深的元素和同级元素,在另一种情况下设置为所有元素。第二种情况比第一种情况快 10 倍。这证明搜索在找到第一个具有匹配ID的元素后停止。
JavaScript
function Div(el) {
var div = document.createElement('div');
el.appendChild(div);
return div;
}
var i, body, el, t0, t1;
el = body = document.querySelector('body');
for(i=0; i<10000; i++) {
el = new Div(el);
el.setAttribute('id', 'ix'); // <- setting id="id" in this line will produce ~10x time difference
}
el.setAttribute('id', 'id');
el = new Div(body);
el.setAttribute('id', 'id');
t0 = performance.now();
document.getElementById('id');
t1 = performance.now();
console.log('Time to find element by ID: ' + (t1 - t0) + 'ms');
笨蛋
关于javascript - document.getElementById() 如何搜索 DOM 树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30371253/