Does document.getElementById
in JavaScript return a live DOM element? I am interested to know for performance reason
-
2What would you consider a "live" DOM element, and what would a "non-live" DOM element look like ?– adeneoCommented Oct 2, 2013 at 19:22
-
elementList = document.querySelectorAll(selectors); elementList is a non-live NodeList of element objects.– GibboKCommented Oct 2, 2013 at 19:24
-
Can you give an example of what a live element does?– tymeJVCommented Oct 2, 2013 at 19:24
-
If you mean "live" like after edited the DOM, the answer is yes.– Fabien SaCommented Oct 2, 2013 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.– PointyCommented Oct 2, 2013 at 19:25
2 Answers
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.
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.– Community BotCommented Jul 27, 2023 at 15:08