JavaScript: How to Iterate/Loop HTML Elements

By Xah Lee. Date: . Last updated: .

The DOM get elements methods return either HTMLCollection or NodeList

How do you iterate them?

After JS2015

Since JS2015, both HTMLCollection and NodeList are Iterable Object.

Use for-of Loop. e.g.

for (let x of document.querySelectorAll("*")) = "revert";

or use Spread Operator to turn it to array. e.g.

[...document.querySelectorAll("*")].forEach((x) => { = "revert";

or use JavaScript: Array.from to turn it into array. e.g.

Array.from(document.querySelectorAll("*")).forEach((x) => { = "revert";

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