Grow your CSS skills. Land your dream job.

Last updated on:

Loop Over querySelectorAll Matches

You can loop over Arrays really easily in JavaScript with forEach, but unfortunately it's not that simple with the results of a querySelectorAll.

/* Will Not Work */
document.querySelectorAll('.module').forEach(function(){
  
});

That's because what you get back from querySelectorAll isn't an Array, it's a (non-live) NodeList.

Here's a quick way to iterate over all the found elements though:

var divs = document.querySelectorAll('div );

[].forEach.call(divs, function(div) {
  // do whatever
  div.style.color = "red";
});

You could also use a classic for loop:

var divs = document.querySelectorAll('div'), i;

for (i = 0; i < divs.length; ++i) {
  divs[i].style.color = "green";
}

There are also for..of loops, but...

/* Be warned, this only works in Firefox */

var divs = document.querySelectorAll('div );

for (var div of divs) {
  div.style.color = "blue";
}

This is pretty intense (probably dangerous and generally not recommended) but you could make NodeList have the same forEach function as Array does, then use it.

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

var divs = document.querySelectorAll('div').forEach(function(el) {
  el.style.color = "orange";
})

There is a bit more information in the MDN article.

Comments

  1. Aneece
    Permalink to comment#

    The safer way to do the last version and co-opt the Array method would be to do something like this:

    Array.prototype.forEach.call(document.querySelectorAll('div'), function(div) { console.log(div); })
    

    Of course, you still need to make sure you have a polyfill for Array.forEach if you’re targeting older browsers.

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".