The most powerful way to select multiple DOM elements in JavaScript
document.querySelectorAll() returns a static NodeList of all elements
that match a specified CSS selector(s).
// Select all paragraphs
const paragraphs = document.querySelectorAll("p");
paragraphs.forEach(p => {
console.log(p.textContent);
});
You can use any valid CSS selector:
// By class
document.querySelectorAll(".item");
// By ID inside a container
document.querySelectorAll("#menu a");
// Nested selectors
document.querySelectorAll("div.card h2");
Unlike getElementsByClassName(), the NodeList returned by
querySelectorAll() does not automatically update when the DOM changes.
Practice using selectors in your browser DevTools and experiment with real DOM structures.
Mastering querySelectorAll() is essential for modern frontend development.