JavaScript iterate through NodeList [duplicate]
Asked Answered
J

2

54

I am looking for a best way to iterate through NodeList excluding length. I am using:

var foo =  document.querySelectorAll('[id^=foo_id]')
console.log(foo)

Returned NodeList has all the required elements + the last entry of length:.

  0: input#foo_id_...
  1: input#foo_id_...
  ..................
  n: input#foo_id_...
  length: n+1

I wonder what the most efficient way to iterate through that NodeList. I can utilize list length etc, but would like to know if there is a more "elegant" way.

Jemy answered 11/7, 2019 at 13:34 Comment(3)
The first line of code in your question is invalid.Syrian
What have you tried? What inefficiencies did you find?Unpaidfor
Also dupe of Looping through a nodelist JS.Unpaidfor
S
74

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

Syrian answered 11/7, 2019 at 13:38 Comment(3)
@hereticMonkey but burgers are better than pizza (thats just an unjustified claim in bold, not sure where the point is) Also that answer is deprecated, just as this one. There is NodeList.forEach, use it.Phosphorescent
You can also use a for...of loop. for (const el of foo) {...}Leucotomy
caniuse.com/?search=NodeList.forEachStretto
H
4

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

See also Why doesn't nodelist have forEach?

Hautesalpes answered 11/7, 2019 at 13:37 Comment(1)
@neuhas vanilla.js already have inbuilt forEach for nodeList. developer.mozilla.org/en-US/docs/Web/API/NodeListParachronism

© 2022 - 2024 — McMap. All rights reserved.