Lesson 9 of 28
In progress
Selecting elements
Find elements with querySelector, handle the null case, and scope queries so one component cannot grab another's markup.
Everything you do to a page starts with finding the right element. The selection API is small, and most DOM bugs are a selector that matched nothing or matched more than you expected.
What you will learn
- Select one element and many with
querySelectorandquerySelectorAll. - Handle a missing element without a crash.
- Scope a query to a component and read
data-*attributes.
One element
Editable. Runs in your browser.
<script>
const title = document.querySelector("#title");
const lead = document.querySelector(".lead");
console.log(title.textContent);
console.log(lead.textContent.length);
</script>
Press Run to see the output.
querySelector takes any CSS selector and returns the first match, or null. Ids use #, classes use ., and element names need no prefix. The selector syntax is the same one you learned for CSS, which is why the CSS module came first.
getElementById is slightly faster and only works for ids. querySelector is general enough that most code uses it consistently.
Many elements
Editable. Runs in your browser.
<script>
const items = document.querySelectorAll("#list li");
console.log(items.length);
items.forEach((item, index) => {
console.log(index, item.textContent);
});
</script>
Press Run to see the output.
querySelectorAll returns a static NodeList. It has forEach and length, and it does not update when the DOM changes. If you need array methods such as map or filter, convert it: Array.from(items) or [...items].
A live collection, such as getElementsByClassName, does update, which sounds convenient and often causes loops that never end because the collection grows as you append.
The null case
A selector that matches nothing returns null, and the next property access throws.
Editable. Runs in your browser.
<script>
const missing = document.querySelector("#does-not-exist");
console.log(missing);
if (missing) {
missing.textContent = "This line never runs";
}
const panel = document.querySelector("#panel");
if (panel) {
panel.textContent = "Updated safely";
}
</script>
Press Run to see the output.
Guard when the element is optional, and fail loudly when it is required. A guard that silently does nothing hides a typo; a thrown error points at the line. In practice, required elements in your own template can be selected without a guard, and optional ones get one.
Modern JavaScript also offers optional chaining: document.querySelector("#x")?.classList.add("active"). It is compact, and it hides the failure just as effectively, so use it when absence is expected.
Scoping and closest
Queries run from document by default, which means a component can accidentally grab another component’s element. Scope the query to a container instead.
Editable. Runs in your browser.
<script>
const second = document.querySelector("#second");
const button = second.querySelector("button");
console.log(button.textContent);
const clicked = document.querySelector("#first button");
console.log(clicked.closest(".card").id);
</script>
Press Run to see the output.
closest walks up from an element to the nearest ancestor matching a selector, including the element itself. It is the backbone of event delegation: from the clicked target, find the component that owns it.
Cache what you reuse
If a function runs on every keystroke and queries the same container each time, select once and keep the reference. A cached element stays usable as long as the node is in the document; replacing the container’s markup invalidates it, so cache the stable parent rather than a child you re-render.
Editable. Runs in your browser.
function stamp() {
const output = panel?.querySelector("p");
if (output) output.textContent = "Updated by script";
}
stamp();
Press Run to see the output.
querySelectorAll is a snapshot. If you add an item after selecting, the NodeList does not include it, and iterating the old list leaves the new item unprocessed. Re-query after a change, or keep the data as the source of truth and render from it, which is exactly the pattern the project later in this module follows, and the reason it keeps its data outside the DOM.
Reading data attributes
Editable. Runs in your browser.
<script>
const button = document.querySelector("[data-action='delete']");
console.log(button.dataset.action);
console.log(button.dataset.id);
</script>
Press Run to see the output.
data-* attributes become dataset properties in camelCase: data-task-id is dataset.taskId. They are the standard way to attach an id or a mode to markup without inventing classes for data.
Values are always strings. Convert with Number(dataset.id) before comparing to a numeric id.
Selecting inside a loop with document.querySelector instead of the current item is a common source of "it always changes the first one". Inside a forEach, use the item or its parent as the query root, not document.
Given three cards, select them all, log the text of the one with data-featured="true", and add a class to every card whose button has data-action="save".
Show solution
Editable. Runs in your browser.
<script>
const cards = […document.querySelectorAll(".card")];
const featured = document.querySelector("[data-featured='true']");
console.log(featured.textContent.trim());
cards.forEach((card) => {
if (card.querySelector("[data-action='save']")) {
card.classList.add("has-save");
}
});
console.log(cards.filter((card) => card.classList.contains("has-save")).length);
</script>
Press Run to see the output.
Spreading the NodeList makes filter available. Each query is scoped to its own card, so the check cannot inspect a neighbour.
Recap
querySelectorreturns one element or null;querySelectorAllreturns a static NodeList.- Guard optional elements and scope queries to a container.
closestanddatasetconnect an event target back to the component and its data.
Next, you will change what an element says and how it looks.
Is querySelector slow?
Why does my NodeList not have map?
Progress is saved in this browser only. No account, no email.