JavaScript
querySelectorAll
Learn to select multiple elements and get them as a NodeList.
Multiple elements with querySelectorAll
querySelectorAll selects all elements matching a CSS selector and returns them as a NodeList. While querySelector gives only the first match, this method collects every match.
Example: document.querySelectorAll(".item") gives every element with class item. The returned list is array-like; it has a length property and index access like [0].
If there are no matching elements, the list is empty (length zero); it does not return null.
for...of over a NodeList
The NodeList returned by querySelectorAll can be traversed with a for...of loop. This is similar to using for...of on arrays.
Example:
const items = document.querySelectorAll(".item");
for (const item of items) {
console.log(item.textContent);
}
At each loop step, item represents a single element; just like the object returned by querySelector.
Exercise Print the text of every element
Select all elements with class "task" using querySelectorAll and assign them to tasks. Then loop over each with for...of and print task.textContent with console.log.
Show example solution
Select with querySelectorAll('.task'), loop with for (const task of tasks), inside write console.log(task.textContent).
Example solution:
const tasks = document.querySelectorAll(".task");
for (const task of tasks) {
console.log(task.textContent);
}
Test yourself
-
What does querySelectorAll return?
- A single element or null
- All matches as a NodeList
- A plain JavaScript array
- The HTML tag itself
Show answer
All matches as a NodeList — Correct! It returns all matches as a NodeList.
-
Complete the loop
const items = document.querySelectorAll(".item");
for (const item of ____) {
console.log(item.textContent);
}
Show answer
const items = document.querySelectorAll(".item");
for (const item of items) {
console.log(item.textContent);
}
-
Match each method to its return value
- getElementById
- single element or null
- querySelector
- first matching element or null
- querySelectorAll
- NodeList (may be empty)
- document.title
- the page title (string)
-
What does querySelectorAll return when no elements match?
- It returns null
- It throws an error
- An empty NodeList (length 0)
- It returns undefined
Show answer
An empty NodeList (length 0) — Correct! With no matches it returns an empty NodeList, not null.
Next lesson: textContent and innerText