JS: Iterate HTML Elements

By Xah Lee. Date: . Last updated: .

Iterate HTMLCollection or NodeList

DOM get elements methods return either HTMLCollection or NodeList, both are Iterable Object, since JS2015.

Use for-of Loop.

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

or use Spread Operator to turn it to array.

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

or use JS: Array.from to turn it into array.

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

Before JS2015

For before JS2015 code, HTMLCollection and NodeList are not iterable, but still are Array-Like Object. see Apply Array Method to Array-Like Object

Basic DOM Element Methods

BUY Ξ£JS JavaScript in Depth