Last Updated: December 26, 2018
·
20.5K
· thomaspeklak

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();
})

3 Responses
Add your response

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 ·

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

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

over 1 year ago ·

+1

over 1 year ago ·