The JavaScript querySelectorAll() method
The querySelectorAll() method returns a NodeList of all elements matching a CSS selector. document.querySelectorAll(".item") gets every element with class item. You can loop the result with forEach(). The list is static — a snapshot — so it won't update as the page changes.
Overview
querySelectorAll() is the "give me all of them" version of querySelector(). Pass a CSS selector and you get back a NodeList containing every matching element, in document order. If nothing matches you get an empty list (not null), so it's always safe to loop.
The handy thing is that a NodeList has its own forEach(), so you can iterate directly: document.querySelectorAll(".tab").forEach(tab => ...). It is not a real array, though — it lacks map(), filter() and the rest. When you need those, convert it first with Array.from(list) or the spread operator [...list].
One behavior to know: the list is static. It's a snapshot taken at the moment you call it, so elements added later won't appear in it, and removed ones still will. That's usually fine and predictable. For attaching one handler to many current-and-future elements, event delegation with a single addEventListener() on a parent is often the better pattern.
Syntax
const list = document.querySelectorAll(selectors)
document.querySelectorAll(".item").forEach(el => {
// do something with each el
});
const arr = [...document.querySelectorAll(".item")]; // real array
Parameters
The querySelectorAll() method accepts the following parameters.
| Parameter | Description |
|---|---|
selectors |
A string of one or more CSS selectors. All matching elements are returned as a static NodeList. |
Example
<ul>
<li class="item">One</li>
<li class="item">Two</li>
<li class="item">Three</li>
</ul>
<script>
const items = document.querySelectorAll('.item');
items.forEach((li, i) => {
li.textContent = (i + 1) + '. ' + li.textContent;
if (i % 2 === 0) li.style.fontWeight = 'bold';
});
</script>
Best practices
- Loop directly with
.forEach()— a NodeList supports it. - Convert to an array with
[...list]orArray.from(list)to use map() / filter(). - Remember the list is static — elements added after the call won't be in it.
- For many similar elements, consider event delegation with one addEventListener() on a shared parent.
Frequently asked questions
What does querySelectorAll() return?
NodeList of all elements matching the selector — empty if there are none.How do I loop over querySelectorAll()?
.forEach() directly: document.querySelectorAll(".x").forEach(el => { ... }).Is a NodeList an array?
forEach() but not map() or filter(). Convert it with [...list] or Array.from(list) to use array methods.