Does document.getElementById return a live dom element?

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

Answers:

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.