Skip to main content

How to Select All Matching Elements with querySelectorAll in JavaScript

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

document.querySelectorAll(selector) gives you every element on the page that matches a CSS selector, as a list you can loop over with for...of. When nothing matches, the list is empty, so a loop over it simply doesn't run.

Syntax​

Syntax
const <list> = document.querySelectorAll(<selector>);

for (const <element> of <list>) {
<statements>
}
PartWhat it does
<selector>A CSS selector, as a string, such as 'li', '.sale' or 'input[name=size]'.
<list>The result: a NodeList with every matching element, in the order they appear in the page. <list>.length is how many there are.
<element>In the loop, one element of the list at a time.
<statements>What to do with each element.

MDN's Document: querySelectorAll() method page calls the result a static NodeList: a snapshot taken when you call it.

The Example​

The example page has a list of three items. The script selects all of them with querySelectorAll('li'), turns each one's text into capitals, and shows how many there were.

Step 1: Write the Code​

Create a file named index.html in a text editor, such as Visual Studio Code:

index.html, a page with a list of Apples, Bread and Cheese, an empty paragraph with the id count, and a script that loops over document.querySelectorAll('li') to make each item's text upper case, then writes items.length plus the word items into the paragraph.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>querySelectorAll</title>
</head>
<body>
<ul>
<li>Apples</li>
<li>Bread</li>
<li>Cheese</li>
</ul>
<p id="count"></p>

<script>
const items = document.querySelectorAll('li');
for (const item of items) {
item.textContent = item.textContent.toUpperCase();
}
document.getElementById('count').textContent = items.length + ' items';
</script>
</body>
</html>

for (const item of items) runs its block once for each element in the list. toUpperCase() returns the text in capitals, and the loop puts it back into the item.

Step 2: Open It in a Browser​

Double-click index.html. It opens in your browser:

The page in Chromium: a bulleted list of APPLES, BREAD and CHEESE in capitals, and below it 3 items.

The screenshot comes from Chromium 159, the open-source browser that Chrome is built on.

What Happened​

  • querySelectorAll('li') returned all three items, not just the first.
  • The loop changed each one, so the whole list is in capitals.
  • items.length was 3, the number of elements in the list.

Common Mistakes​

MistakeWhat happensDo this instead
Calling an array method the list doesn't have, .mapTypeError: document.querySelectorAll(...).map is not a functionLoop with for...of, or make an array first: Array.from(items).map(...)
Setting a property on the whole list, items.textContent = 'x'Nothing changes on the page: the list isn't an elementSet it on each element inside a loop
Expecting the list to grow when you add elementsAfter a fourth <li> was added, the old list still had 3 items, while a new querySelectorAll call found 4Call querySelectorAll again after you change the page
Using querySelector when you mean all of themOnly the first match changesUse querySelectorAll

Troubleshooting​

SymptomLikely causeFix
The loop never runsNothing matched, so the list is empty: length is 0Check the selector, and put the <script> after the elements
... is not a function on the listThe list is a NodeList, which has forEach but no map or filterUse Array.from(list) to get an array
New elements are left outThe list was taken before they were addedSelect again after adding them

FAQ​

How do I turn the list into an array?​

Array.from(items) makes an array, with every array method. On this page, Array.from(document.querySelectorAll('li')).map((li) => li.textContent) returned [ 'APPLES', 'BREAD', 'CHEESE' ].

Can I use forEach instead of for...of?​

Yes, a NodeList has forEach: items.forEach((item) => ...) works the same way as the loop here.

What does it return when nothing matches?​

An empty NodeList, not null. document.querySelectorAll('.missing').length was 0, and looping over it doesn't throw an error.

Conclusion​

querySelectorAll collects every element a selector matches, and for...of lets you handle them one by one. Remember that the list is a snapshot without array methods: select again after the page changes, and use Array.from when you need map or filter.

Additional Resources​