JavaScript iterate through NodeList [duplicate]

Solution 1:

The simplest way is a for loop:

for (let i = 0; i < foo.length; i++) {
  // Do stuff
}

This is the best solution, as pointed out here it's bad practice to use array methods or convert a NodeList to an array - use a different variable if you need to, but a for loop is all you need to loop over a NodeList. (Thanks Heretic Monkey for pointing this out to me).

If you want to use array methods like forEach, map, etc., it's best convert to an array first - this is incredibly simple with spreading:

[...foo].forEach(e /* Do stuff */);

If you want to specifically use map, use Array.from as the second argument is the callback to be applied to map.

Array.from(foo, e => /* .map callback */);

And in older environments:

Array.prototype.slice.call(foo).forEach(e => /* Do stuff */);

(I know that you can use array methods on a NodeList, but it's easier if you stick to using one data type.)

Solution 2:

Although NodeList is not an Array, it is possible to iterate over it with forEach()

See also Why doesn't nodelist have forEach?