The browser
querySelector and querySelectorAll
Find elements on the page with the same selector language you use in CSS.
Why it exists
Before you can change something on a page, you have to find it. There used to be several different methods for that — getElementById, getElementsByClassName, getElementsByTagName — and complex conditions had to be assembled by hand. querySelector takes any CSS selector: the same language you already use to describe elements in your styles. One method instead of five, and no new syntax.
Where it's used
- Find an element to change it: a heading, the cart counter, a field's error message.
- Go through all similar elements: mark sold-out products, deselect every tab.
- Search inside a card:
card.querySelector(".price")— the price of this card, not the first one on the page. - UI tests: "find the Buy button and click it".
Syntax
document.querySelector("#menu") // by id
document.querySelector(".dish") // by class: the first one
document.querySelectorAll("#menu li") // every li inside #menu
menu.querySelector("[data-id=\"7\"]") // by attribute, inside menuExamples
function showTitle(text) {
const title = document.querySelector("#title");
if (title) title.textContent = text;
}
function dishNames() {
return [...document.querySelectorAll(".dish")].map((li) => li.textContent);
}const page = {
tag: "body",
children: [
{ tag: "h1", text: "Purrfect Café", children: [] },
{
tag: "ul",
children: [
{ tag: "li", text: "Latte", children: [] },
{ tag: "li", text: "Cheesecake", children: [] },
],
},
],
};
function find(node, test) {
if (test(node)) return node;
for (const child of node.children) {
const found = find(child, test);
if (found) return found;
}
return null;
}
find(page, (node) => node.tag === "li").text; // → "Latte"
find(page, (node) => node.tag === "table"); // → nullquerySelector: walk top to bottom, depth first; the first match — or null.function markSoldOut(names) {
for (const li of document.querySelectorAll("#menu li")) {
li.classList.toggle("sold-out", names.includes(li.dataset.name));
}
}
// markSoldOut(["Cheesecake"]) strikes out the cheesecake and unmarks the restquerySelectorAll + for...of: change every element found.function cardPrice(card) {
return Number(card.querySelector(".price").textContent);
}
// Search inside the card, not the whole page:
// every card has its own .priceResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
The selector is read exactly as in CSS: #id, .class, tag, [attribute="value"], nesting with a space (#menu li), direct children with >.
querySelector walks the tree in document order — top to bottom, depth first — and stops at the first match. If nothing matches, it returns null.
querySelectorAll collects every match into a NodeList. It's a snapshot: elements added later won't show up in it. A NodeList has length and forEach and works with for...of, but it has no map or filter — for those, turn it into an array: [...list] or Array.from(list).
Called on an element (card.querySelector(…)), it searches only that element's descendants — faster and more precise than the whole page.
Traps
How it differs from…
When to pick something else
Don't look an element up again on every event in a hot loop — store it in a variable once. And if you've just created an element with createElement, there's no need to search for it: you already hold a reference to it.