Lesson 9 of 28

In progress

Course progress

JavaScript

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 querySelector and querySelectorAll.
  • Handle a missing element without a crash.
  • Scope a query to a component and read data-* attributes.

One element

HTML
Editable. Runs in your browser.





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

HTML
Editable. Runs in your browser.





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.

HTML
Editable. Runs in your browser.





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.

HTML
Editable. Runs in your browser.





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.

JavaScript
Editable. Runs in your browser.





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

HTML
Editable. Runs in your browser.





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
HTML
Editable. Runs in your browser.





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

  • querySelector returns one element or null; querySelectorAll returns a static NodeList.
  • Guard optional elements and scope queries to a container.
  • closest and dataset connect 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?
For normal pages the difference is negligible. Calling it thousands of times inside a loop is the case worth caching a reference for.
Why does my NodeList not have map?
It is not an array. Convert with Array.from or spread when you need array methods.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.