12

Does document.getElementById in JavaScript return a live DOM element? I am interested to know for performance reason

8
  • 2
    What would you consider a "live" DOM element, and what would a "non-live" DOM element look like ?
    – adeneo
    Commented Oct 2, 2013 at 19:22
  • elementList = document.querySelectorAll(selectors); elementList is a non-live NodeList of element objects.
    – GibboK
    Commented Oct 2, 2013 at 19:24
  • Can you give an example of what a live element does?
    – tymeJV
    Commented Oct 2, 2013 at 19:24
  • If you mean "live" like after edited the DOM, the answer is yes.
    – Fabien Sa
    Commented 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.
    – Pointy
    Commented Oct 2, 2013 at 19:25

2 Answers 2

15

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.

HTML for the example:
<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.

0
0

yeah only certain getEleme and querySele functions return live node lists

1
  • 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 Bot
    Commented Jul 27, 2023 at 15:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.