How does document.getElementById () look for the DOM tree?
I know that some browsers (most today?) Compile a hash table of all elements with an ID. So, in this case, calling document.getElementById () might just do a lookup in the Hash table. But how to do it otherwise in the context of a DOM tree - is it, for example, depth-first search?
I ask because I want to know where would be the fastest place to place a DOM element, so it is searched as soon as or close to the start of the actual launch.
Had a quick glance and couldn't find any information on the matter.
Significant responsibility for any help.
source to share
Since the DOM implementation is browser dependent, each browser may implement it differently. There is also the possibility that the browser has a hashmap for all ids and executes document.getElementById
with it.
To understand in which order the browser views the DOM, you can look at a collection document.all
containing a simple list of all DOM elements in document
. In the case of Chrome, Safari and Firefox, it looks like DFS.
Another interesting question: if two elements in the same document have the same ID that will be returned document.getElementById
. Using the snippet below, you can see that this is the first item found using the DFS algorithm (at least in the browsers mentioned below).
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'));
Console output
DFS
Plunker
http://plnkr.co/edit/jaUolyxwrZcXsNXwkmtm?p=preview
Edit:
Regarding the additional question in the comment to the answer
I'm not sure if the search will stop at the location of the first result, which of course will be faster ... is there a way to test this at all?
Below you can find a piece of code that creates 10000 elements one inside the other and one sibling element. In one case, the same identifier is set to the deepest element and the element to be related, in the other for all elements. The second case is ~ 10 times faster than the first. This proves that the search stops after the first element with a matching ID is found.
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');
Plunker
source to share