How to select DOM elements with querySelector and querySelectorAll
· Category: JavaScript
Short answer
querySelector returns the first matching element, while querySelectorAll returns a static NodeList of all matches. Both accept any valid CSS selector string.
Steps
- Select a single element:
javascript const header = document.querySelector("#main-header"); - Select multiple elements:
javascript const items = document.querySelectorAll(".list-item"); items.forEach(el => el.classList.add("active")); - Use complex CSS selectors:
javascript const btn = document.querySelector('nav button[data-action="save"]'); - Scope queries within a parent element:
javascript const card = document.querySelector(".card"); const title = card.querySelector(".title");
Tips
- Prefer
querySelectorovergetElementByIdfor consistency, though the latter is slightly faster. querySelectorAllreturns a NodeList, not an Array; useArray.from()or the spread operator if you need array methods likemap.
Common issues
- Forgetting that
querySelectorAllis static; it does not update automatically when the DOM changes. - Using overly broad selectors that match unexpected elements and hurt performance.