Every modern JavaScript page is built out of elements, and your code has to find those elements before it can change them. The querySelector and querySelectorAll methods are how you do that. You hand them a CSS selector and they give you back the first match or every match. This lesson explains what each one returns, how to search inside one panel instead of the whole page, how to walk up to an ancestor element, and the two mistakes that fail quietly instead of loudly.
The previous lesson in this module covered the modern syntax that you will use in every example here, and the next lesson takes the elements that you select in this one and changes their text, their attributes, and their classes.
Why querySelector became the default way to pick elements
The DOM started with a narrow vocabulary. There was getElementById, getElementsByTagName, and getElementsByClassName. Each one of them was a special-purpose lookup, and not one of them could express a relationship between elements. There was no way to ask for "the second link inside every list item that has the class active", and browser support for the different methods varied enough that whole libraries existed just to paper over the differences.
querySelector replaced that pile with a single method that speaks the CSS selector syntax that you already use in your stylesheets. One method covers ids, classes, attributes, descendant combinators, and pseudo-classes such as :checked or :nth-child. Because it is built on the same selector engine as CSS, there is no second dialect to learn, and a selector that works in your stylesheet works here as well.
Here is the page that these examples run against. The structure is deliberately ordinary, because the point of the lesson is the selection code and not the markup.
<nav class="sidebar" id="sidebar">
<ul id="menu">
<li class="nav-item"><a href="#home" data-id="home">Home</a></li>
<li class="nav-item"><a href="#reports" data-id="reports">Reports</a></li>
<li class="nav-item"><a href="#settings" data-id="settings">Settings</a></li>
</ul>
</nav>
<main id="main">
<h1 id="page-title">Dashboard</h1>
<section id="panel-reports" class="panel">
<h2>Weekly reports</h2>
<table><tbody>
<tr><td>Mon</td><td>42</td></tr>
<tr><td>Tue</td><td>57</td></tr>
</tbody></table>
</section>
<section id="panel-settings" class="panel">
<h2>Settings</h2>
<p class="muted">Nothing to configure yet.</p>
</section>
</main>
What does querySelector return compared with querySelectorAll?
querySelector returns a single element. It is the first match in document order, or null when nothing matches at all. querySelectorAll returns a NodeList that holds every match in document order, and an empty NodeList when nothing matches.
That difference decides how you write the code around the call. A single result is used directly, and every use of it needs a null check. A list result is looped over, so an empty list is harmless and no guard is needed. Mixing the two up is the source of the classic Cannot read properties of null crash. You called querySelector, stored the result, and then used it without checking whether it was there.
// querySelector gives you the FIRST match, or null.
const firstLink = document.querySelector(".nav-item a");
// querySelectorAll gives you EVERY match as a NodeList.
const allLinks = document.querySelectorAll(".nav-item a");
console.log(firstLink.textContent); // "Home"
console.log(allLinks.length); // 3
console.log(firstLink.getAttribute("href")); // "#home"
// A NodeList is array-LIKE, not an Array.
console.log(typeof allLinks.map); // "undefined"
console.log(typeof allLinks.forEach); // "function"
The last two lines matter more than they look. A NodeList supports length, index access, forEach, and for...of. It does not support map, filter, or reduce. When you want one of those, convert the list into a real array first with the spread operator, and then use [...allLinks].map(...). Spreading also gives you an array that you can sort or copy.
How do I search inside one element instead of the whole page?
Every element has its own querySelector and querySelectorAll methods, and they only look at the descendants of that element. panel.querySelector("h2") finds the first heading inside the panel, and it will never reach for a heading that lives somewhere else on the page. Scoping like this keeps a part of the page self-contained, and it is faster as well, because the browser can skip the parts of the tree that are not underneath the element that you started from.
const panel = document.querySelector("#panel-reports");
const heading = panel.querySelector("h2");
const firstCell = panel.querySelector("tbody tr td");
const rows = panel.querySelectorAll("tbody tr");
console.log(heading.textContent); // "Weekly reports"
console.log(firstCell.textContent); // "Mon"
console.log(rows.length); // 2
console.log(panel.querySelectorAll("h2").length); // 1
Two details catch people out here. First, the scoped search still walks through descendants, so panel.querySelector("#menu") finds nothing even though #menu exists on the page, because #menu is not inside the panel. Second, scoping does not change what a selector means. tbody tr td means a cell inside a row inside a table body, and the element that you scope to has to be an ancestor of the whole chain for it to match.
How do I find the element a click actually landed on?
When you listen for events on a container, the object that is handed to your callback is the element that the event physically struck. That might be a span inside a button inside a list row, while what you usually want is the row. closest answers exactly that question. Given a selector, it walks up from the starting element one ancestor at a time and returns the first one that matches. It checks the element itself before it moves upward, so el.closest("li") on a list item returns that same list item.
Pair closest with the dataset object to read the identifying details off the matched element. Every data-* attribute becomes a camelCase key, so data-id="reports" is read as element.dataset.id.
const menu = document.querySelector("#menu");
const target = menu.querySelector('[data-id="reports"]');
const listItem = target.closest("li");
const sidebar = target.closest(".sidebar");
console.log(target.dataset.id); // "reports"
console.log(listItem.tagName); // "LI"
console.log(listItem.className); // "nav-item"
console.log(sidebar.id); // "sidebar"
Should I still use getElementById?
There is nothing wrong with it. getElementById is fast, it is supported everywhere, and it returns the element or null, so it behaves in the same way as querySelector("#some-id"). The only real difference is that one is a single-purpose lookup and the other accepts any CSS selector, which means you can move from an id to a class or to an attribute selector without changing the method that you call.
The methods that are worth retiring are the plural ones that return an HTMLCollection. Unlike the NodeList that comes from querySelectorAll, an HTMLCollection is live. It updates itself as the document changes, so a collection that you stored earlier may hold different elements than it did when you captured it. That behaviour is convenient right up until it quietly breaks a loop that you are in the middle of.
| Call | Returns | Live? |
|---|---|---|
querySelector(sel) | First element or null | No |
querySelectorAll(sel) | Static NodeList | No |
getElementById(id) | Element or null | No |
getElementsByClassName(c) | HTMLCollection | Yes |
getElementsByTagName(t) | HTMLCollection | Yes |
Which selector mistakes break silently?
The first quiet failure is a stale collection. A NodeList is a snapshot that was taken at the moment you called querySelectorAll. If you add a new matching element afterwards, the snapshot does not grow, which quietly breaks any code that assumed the list keeps track of the page.
const menu = document.querySelector("#menu");
const items = menu.querySelectorAll(".nav-item");
const extra = document.createElement("li");
extra.className = "nav-item";
extra.textContent = "Audit";
menu.append(extra);
console.log(items.length); // 3 - a snapshot, not a live view
console.log(menu.querySelectorAll(".nav-item").length); // 4 - a fresh query sees the new row
The second quiet failure is a selector that matches nothing when you expected a match, and that usually happens because of a spacing mistake. .nav-item a means "a link inside something with the class nav-item". .nav-item.a means "one element that has both of those classes". Confusing the two gives you null rather than an error, and the null turns into a crash two lines later, far away from the real cause.
A genuinely invalid selector behaves much better. It throws a SyntaxError that names the offending text, which is far kinder. If you get a null where you expected an element, print the selector and check it character by character before you start debugging the logic around it.
const missing = document.querySelector(".does-not-exist");
console.log(missing); // null
if (missing) {
console.log(missing.textContent);
}
console.log(document.querySelectorAll(".does-not-exist").length); // 0
The selection calls worth memorising
document.querySelector(sel)gives you the first match in the whole document, or null.document.querySelectorAll(sel)gives you a static NodeList of every match.element.querySelector(sel)does the same thing, but restricted to the descendants of that element.element.closest(sel)walks up from an element to the nearest ancestor that matches the selector, and it includes the element itself.element.dataset.namereads adata-nameattribute as camelCase.[...nodeList]turns a NodeList into a real array when you needmaporfilter.
Try it yourself: open any page that you like, open the browser console, and run document.querySelectorAll("a") followed by document.querySelectorAll("a").length. Now add console.log(document.querySelector("main").id) and then change the selector to a tag that does not exist, so that you can see the null for yourself. Next, pick one of the links that you found, store it in a variable, and print link.closest("nav").tagName to see how far up the tree the match sits.