jcmzxw
12.15K
· August 2012 ·
F7624c4a8bf787d53804874361494d1d

Iterate over querySelectorAll result

querySelectorAll results do not provide a way to iterate over them (what a shame!), it should be as simple as:

document.querySelectorAll('.failure').forEach(function(){
  doStuff()
});

nevertheless you can iterate with:

[].forEach.call(
  document.querySelectorAll('.awsome'), 
  function(el){
    doStuffWith(el);
  }
);

with ES1015 you can use the spread operator to make an array from the query selector result:

 [...document.querySelectorAll('.es2016')].forEach(function () {
    doMoreStuff();
})
Sign in or sign up to add your response.

3 Responses

14317
B4e454ae1ef38b6b70334c2987c4448e

It's really stupid that you can use forEach on a result from querySelectorAll. Thanks for the tip tho, it helped me.

over 1 year ago ·
15425
9130fdbc7a477c5d8e2ca62a1abc12ed

NodeList.prototype.forEach = Array.prototype.forEach;
HTMLCollection.prototype.forEach = Array.prototype.forEach;

Quelle: https://gist.github.com/DavidBruant/1016007

over 1 year ago ·
16335
70f0507ce8012cdaa5e0ab97445136c6

+1

over 1 year ago ·