Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does document.getElementById return a live dom element?

Tags:

javascript

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

like image 455
GibboK Avatar asked Oct 02 '13 19:10

GibboK


People also ask

What does document getElementById returns?

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.

Is getElementById a DOM method?

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.

What is the type of data returned by getElementById () method?

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.

How do I know if my element is still in DOM?

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.


1 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.

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.

like image 134
zzzzBov Avatar answered Oct 31 '22 03:10

zzzzBov