JS DOM: Live Object
Where live object came from
Many DOM get element methods return a live object.
HTMLCollectionis always live.NodeListmay or may not be live.
What is a live object
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.
🛑 warning: infinite loop
For example, if you use x = document.getElementsByTagName("p") and use for-loop by checking x.length, and for each iteration you add a new "p" element, it'll be a infinite loop, because the number of items (the x.length) also gets updated.
live object not very useful
live object isn't that much useful.
you can convert it to array and it stops being live, by Array.from
Array.from( document.getElementsByClassName("x"), (x) => { x.style.color = "red"; }, );
Example of live object
// demo of live object const xx = document.getElementsByTagName("vwpgw"); // does not exist console.log(xx.length === 0); // insert a vwpgw tag into document body document.body.appendChild(document.createElement("vwpgw")); // the result got updated console.log(xx.length === 1);