I thing that if .getElementById
were available on all nodes, there would be two main advantages:
It could be possible to select nodes which don't belong to the document.
For example, I would like to do something like
function foo(html){
var el = document.createElement('div');
el.innerHTML = html;
var target = el.getElementById('target');
/* Do something with `target` */
}
But I can't because I get
TypeError: el.getElementById is not a function
.
Then, I don't want to use a class instead of an id, I must do
function foo(html){
var el = document.createElement('div');
el.innerHTML = html;
document.body.appendChild(el);
var target = document.getElementById('target');
document.body.removeChild(el);
/* Do something with `target` */
}
But the document could already have an element with
id=target
. Then, I should do
function foo(html){
var iframe = document.createElement('iframe');
iframe.onload = function(){
var doc = iframe.contentDocument || iframe.contentWindow.document,
el = document.createElement('div');
el.innerHTML = html;
doc.body.appendChild(el);
var target = doc.getElementById('target');
document.body.removeChild(iframe);
/* Do something with `target` */
};
iframe.src = 'about:blank';
document.body.appendChild(iframe);
}
But the code above doesn't work if I want
foo
to return something related withhtml
, because the main code runs after, with theonload
event.It could increase the performance, if the document has lots of elements and you know that the element you are searching is a descendant of an element that you already have in a variable
For example, if I have a document with the following structure:
<body>
<div id=div-1>
<div id=div-1-1>
<div id=div-1-1-1>
...
</div>
<div id=div-1-1-2>
...
</div>
...
</div>
<div id=div-1-2>
<div id=div-1-2-1>
...
</div>
<div id=div-1-2-2>
...
</div>
...
</div>
...
</div>
<div id=div-2>
<div id=div-2-1>
<div id=div-2-1-1>
...
</div>
<div id=div-2-1-2>
...
</div>
...
</div>
<div id=div-2-2>
<div id=div-2-2-1>
...
</div>
<div id=div-2-2-2>
...
</div>
...
</div>
...
</div>
...
</body>
And I do...
var el1 = document.getElementById('div-9999999'),
el2 = document.getElementById('div-9999999-1-2'),
el3 = document.getElementById('div-9999999-1-2-999999'),
el4 = document.getElementById('div-9999999-1-2-999999-1-2-3-4-5');
... it could be much slower than
var el1 = document.getElementById('div-9999999'),
el2 = el1.getElementById('div-9999999-1-2'),
el3 = el2.getElementById('div-9999999-1-2-999999'),
el4 = el3.getElementById('div-9999999-1-2-999999-1-2-3-4-5');
(Of course, this example is a simplification, and in this case using
.childNodes[]
or.children[]
would be much better);
Then, why doesn't .getElementById
work on a node? I don't see any disadvantage, only advantages