DOM: What Does Live Object Mean?

By Xah Lee. Date: . Last updated: .

JavaScript DOM Methods such as document.getElementsByClassName() returns a live NodeList or HTMLCollection.

What does live object mean?

the DOM spec says:

If a collection is live, then the attributes and methods on that object must operate on the actual underlying data, not a snapshot of the data.

[see DOM: Get Elements by ID, Tag, Name, Class, CSS Selector]

For example, if you use es = document.getElementsByTagName("p") and use for-loop by checking es.length, and for each iteration you add a new "p" element, it'll be a infinite loop, because the number of items (the es.length) also gets updated.

Here is another example. When you get a element of β€œh6”, if there's none, but if later a h6 element is inserted to the page, your previous get result magically contains the item.

Evaluate the following line by line in your browser console. [see How to Use Browser Console]

// demo of live object

const x = document.getElementsByTagName("h6");

x.length // is 0

// insert a h6 tag into document body

// our selection of h6 got updated
x.length // is 1

Note: not all get element methods return a live object. {document.getElementById(), document.querySelectorAll()} return non-live object.

[see DOM: Get Elements by ID, Tag, Name, Class, CSS Selector]

[see DOM: NodeList vs HTMLCollection]

How to Think About Live Object?

Live object is not intuitive. You can think of it as delayed evaluation or lazy evaluation. Method or property of live object is re-computed when their result is accessed.

What is the Use of Live Object?

One use, is that you can bind data to elements in charts, such as stock quotes. When the data changes, the plot automatically changes. [see Practical SVG Tutorial]

JavaScript in Depth

DOM Scripting Tutorial


Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc