JS DOM: Loop thru nodes

By Xah Lee. Date: . Last updated: .

Go thru htmlcollection or nodelist

for (let x of document.querySelectorAll("*")) x.style.color = "red";

Convert to array

note, when a Live Object is converted to array, result is not live.

Array.from(
 document.getElementsByClassName("x"),
 (x) => {
  x.style.color = "red";
 },
);

Live object converted to array is non-live

// live object, once converted to array, is no longer live

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);

History

Before JS2015, HTMLCollection is not iterable, nor NodeList.