What You'll Learn
You'll learn how to select multiple elements at once using CSS selectors and work with the collection that comes back.
The Core Idea
While document.querySelector() finds the first matching element, document.querySelectorAll() finds all elements that match your CSS selector. It returns a NodeList — essentially a snapshot list of all matching elements at the moment you run the query.
Think of it like this: if querySelector() is pointing to one specific person in a crowd, querySelectorAll() is pointing to everyone wearing red shirts. You get a list of all matches.
How It Works
// Select ALL paragraphs in the document
const allParagraphs = document.querySelectorAll('p');
// Select ALL elements with class "card"
const allCards = document.querySelectorAll('.card');
// Select ALL links inside a navigation
const navLinks = document.querySelectorAll('nav a');
The returned NodeList looks array-like and has a length property. You can loop through it:
const buttons = document.querySelectorAll('.btn');
// Loop through each button
buttons.forEach(function(button) {
console.log(button.textContent);
});
Static vs Live (Important!)
Remember from your earlier lesson that NodeLists can be live or static. The NodeList from querySelectorAll() is static — it's a snapshot. If you add more matching elements to the page after running the query, they won't appear in your existing NodeList. You'd need to run querySelectorAll() again.
When to Use It
Use querySelectorAll() when you need to work with multiple elements at once — applying the same style change, adding event listeners to a group, or collecting data from several inputs.
Key Takeaway: document.querySelectorAll() selects all elements matching a CSS selector and returns a static NodeList snapshot — perfect for batch operations on multiple elements.