JavaScript: querySelectorAll
querySelectorAll() returns a collection of every element that matches a CSS selector.
What you will learn
- How to select and update a group of elements
- How a NodeList behaves
- How querySelectorAll differs from a live HTMLCollection
Minimal example
const cards = document.querySelectorAll('.card');
cards.forEach(card => {
card.classList.add('visible');
});If there are no matches, the result is an empty NodeList, so a loop simply performs no work. The collection does not automatically include elements added later.
Common mistakes
- Use
querySelectorwhen you need only the first match. - Do not assume the result is a full Array; convert it with
Array.fromwhen you need array-specific methods. - Keep selectors readable and avoid building them from unsafe user input.