DOM: Live Object

By Xah Lee. Date: . Last updated: .

Many DOM get element methods return either live object or non-live object.

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.

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 is 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
document.body.appendChild(document.createElement("h6"));

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

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/DOM: Node Name, Node Type, Node Value

BUY Ξ£JS JavaScript in Depth