Does document.getElementById
in JavaScript return a live DOM element? I am interested to know for performance reason
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
Definition and Usage The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.
The getElementById() method returns the elements that have given an ID which is passed to the function. This function is a widely used HTML DOM method in web designing to change the value of any particular element or get a particular element. If the passed ID to the function does not exist then it returns null.
Use the getElementsByTagName to Check the Existence of an Element in DOM. The function getElementsByTagName() can return all elements with the specified tagName in DOM . The return of the function can be one or more elements or null if no element is found.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With