JS: Iterate HTMLCollection

By Xah Lee. Date: . Last updated: .

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

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

Spread Operator

[...document.querySelectorAll("*")].forEach((x) => {
  x.style.color = "red";
});

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.

Basic DOM Element Methods