JS DOM: Iterate HTMLCollection
Iterate HTMLCollection or NodeList
For-Of Loop
for (let x of document.querySelectorAll("*")) x.style.color = "red";
Convert to Array
🛑 warning: if convert to array, it is no longer Live Object.
Array.from(document.querySelectorAll("*"))
Live Object Converted to Array is Non-Live
// live object, once converted to array, does not reflect update let xx = document.getElementsByTagName("xx"); // returns a live HTMLCollection console.log(xx.length === 0); let x2 = Array.from(xx); // insert a xx tag into document body document.body.appendChild(document.createElement("xx")); // our selection of xx got updated console.log(xx.length === 1); // the converted array did not get update console.log(x2.length === 0);
Before JS2015
Before JS2015, HTMLCollection is not iterable, nor NodeList.
but they still are Array-Like Object.