JavaScript: What Does Live Object Mean?

By Xah Lee. Date: . Last updated: .

JavaScript DOM Methods such as {document.getElementsByTagName(), document.getElementsByClassName(), …} returns a live NodeList or HTMLCollection.

What does live object mean?

the DOM spec DOM Standard#concept-collection 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'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, without you needing to refresh or “pull/push”.

Evaluate the following line by line in your browser console. 〔►see JavaScript: How to Use Browser's JS Console

// demo of live object

var 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 JavaScript: Get Elements by ID, Tag, Name, Class, CSS Selector

〔►see JavaScript: Array vs 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. This technique is used by the library. 〔►see Practical SVG Tutorial

Web Scripting Overview Topic

  1. JavaScript: Browser Window Object, Document Object Model
  2. JavaScript: Intro to Event-Based Programing
  3. JavaScript Execution Order
  4. JavaScript: What Does Live Object Mean?
  5. JavaScript: Array vs NodeList vs HTMLCollection
  6. JavaScript: DOM Whitespace Nodes
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.