Does document.getElementById in JavaScript return a live DOM element? I am interested to know for performance reason
Asked
Active
Viewed 3,612 times
11
GibboK
- 71,848
- 143
- 435
- 658
-
2What would you consider a "live" DOM element, and what would a "non-live" DOM element look like ? – adeneo Oct 02 '13 at 19:22
-
elementList = document.querySelectorAll(selectors); elementList is a non-live NodeList of element objects. – GibboK Oct 02 '13 at 19:24
-
Can you give an example of what a live element does? – tymeJV Oct 02 '13 at 19:24
-
If you mean "live" like after edited the DOM, the answer is yes. – Fabien Sa Oct 02 '13 at 19:24
-
3@GibboK the function returns a reference to the actual DOM element. If, for example, you get a reference to an "input" element, and then afterwards the user types something, you'll see that typing reflected in the "value" property of the object. – Pointy Oct 02 '13 at 19:25
-
How would that example using `querySelectorAll` be any different than using any other method to retrieve an element from the DOM ? – adeneo Oct 02 '13 at 19:25
-
I think [this question](http://stackoverflow.com/questions/7092822/how-to-convert-array-of-live-dom-elements-into-live-nodelist) has some relevance with regards to "live". – ajp15243 Oct 02 '13 at 19:25
-
there is a library called **live_el.js**, to do just that. google **live_el.js** – Akshay Deep Giri Oct 02 '13 at 19:27
2 Answers
14
The distinction between standard and "live" is usually used for lists of elements. document.getElementById returns a single object reference to a DOM node. Once the node is acquired the reference will always point to the same node.
<div id="foo"></div>
JS for the example:
var foo,
bar;
foo = document.getElementById('foo'); //gets the div
bar = document.getElementById('bar'); //null
foo.setAttribute('id', 'bar');
console.log(foo.id); //'bar'
console.log(bar.id); //TypeError
The references don't get updated just because the ID of the element might have changed.
This is in contrast to something like document.getElementsByTagName which returns a list of elements with the given tag. The list will automatically update when elements are added to or removed from the DOM.
zzzzBov
- 174,988
- 54
- 320
- 367
0
yeah only certain getEleme and querySele functions return live node lists
-
Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 27 '23 at 15:08