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's 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 JS: 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

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's 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]

Web Scripting Overview

  1. Browser Window Object, Document Object Model
  2. Intro to Event-Based Programing
  3. JavaScript Load Order
  4. What is Live Object
  5. NodeList vs HTMLCollection
  6. DOM: Whitespace Nodes
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog