Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 156 Β· The DOM

Selecting Elements

Find DOM elements with querySelector, querySelectorAll and getElementById, understand static NodeLists vs live HTMLCollections, and use closest() and matches().

Almost every piece of DOM code starts the same way: find the element you want to work with. The browser gives you several ways to do it, and they don't all behave alike. Some return one element, some return a list; some lists are snapshots, others update themselves as the page changes.

In this lesson you will learn the modern, selector-based methods first, then the older getElement… family and the important difference between a static NodeList and a live HTMLCollection. You will finish with two methods that test or search from an element you already have: matches() and closest().

querySelector() and querySelectorAll()

These two methods accept any CSS selector, so everything you know from CSS Selectors, combinators and pseudo-classes works here too.

  • querySelector(selector) returns the first matching element in document order, or null when nothing matches.
  • querySelectorAll(selector) returns a NodeList of every match. When nothing matches, you get an empty list, never null.
JavaScript
document.querySelector("#cart-total");
document.querySelector("nav a[aria-current='page']");
document.querySelectorAll(".product:not(.sold-out)");
document.querySelectorAll("input[type='checkbox']:checked");
document.querySelectorAll("h2, h3"); // a selector list: both, in document order

The null result is worth planning for. If a selector is wrong or an element is missing, the next line usually fails with TypeError: Cannot read properties of null. When an element is genuinely optional, optional chaining keeps the code safe: document.querySelector(".promo")?.remove().

An invalid selector is different: it throws a SyntaxError immediately, which makes typos easy to spot.

Searching inside an element

Both methods exist on every element, not just on document. Calling them on an element searches only its descendants. This is how you write components that don't accidentally grab parts of the page they don't own.

Scoped searches

There is one subtlety. The selector passed to an element's querySelectorAll() is still matched against the whole document; only the results are limited to descendants. So card.querySelectorAll("section h2") would match the <h2> inside card, because the section part can be satisfied by card itself or even an ancestor outside it. When you want the selector anchored to the element, start it with :scope:

JavaScript
list.querySelectorAll(":scope > li"); // only direct <li> children of list

getElementById() and the older family

document.getElementById("total") finds one element by its id. You pass the bare id, without #. It only exists on document, it is fast, and it is perfectly fine to use. Many developers simply use querySelector("#total") everywhere for consistency; both are correct.

Three older methods return collections:

  • getElementsByClassName("product") β€” elements with that class (you can pass several, space-separated).
  • getElementsByTagName("li") β€” elements with that tag name.
  • document.getElementsByName("size") β€” elements with that name attribute, mostly form fields.

You will see them in existing code. What makes them interesting is that their results are live.

Static NodeList vs live HTMLCollection

querySelectorAll() returns a static NodeList: a snapshot taken at the moment you called it. If elements are added or removed later, the list doesn't change.

getElementsByClassName() and getElementsByTagName() return a live HTMLCollection: it is a view onto the document that always reflects the current state. The children property of an element is live as well.

Static vs live

Click the button a few times. The snapshot stays at 2; the live collection grows. Live collections can surprise you in loops: if you remove elements from the page while looping over a live collection by index, items shift under you and some get skipped. When in doubt, use querySelectorAll() or copy the collection into an array first.

Turning lists into arrays

Neither collection is a real array. A NodeList has forEach(), length, indexing and works with for...of. An HTMLCollection has length, indexing and for...of, but no forEach(). Neither has map(), filter() or reduce().

The fix is to convert to an array with Array.from() or the spread syntax:

JavaScript
const prices = [...document.querySelectorAll(".price")]
  .map((el) => Number(el.textContent))
  .filter((n) => n > 0);

const names = Array.from(document.getElementsByTagName("h2"), (h) => h.textContent);

Once it is an array, every method from map, filter, reduce and forEach is available.

Testing an element with matches()

element.matches(selector) answers a yes-or-no question: would this selector select this element? It doesn't search anything; it just tests. That makes it perfect inside loops and event handlers.

JavaScript
if (field.matches(":invalid")) showHint(field);
if (link.matches("[href^='http']:not([href*='example.com'])")) markExternal(link);

Searching upward with closest()

element.closest(selector) starts at the element itself and walks up through its ancestors, returning the first one that matches. If none does, it returns null. It is the upward partner of querySelector(), which searches down.

closest() is the workhorse of event handling: a click lands on some small element, and you want the card, row or list item that contains it.

closest() and matches()

Click the βœ“ symbol and then the word "Ship". event.target is a <span> in one case and the <button> in the other, but closest("button") finds the button both times. This "click somewhere inside, find the container" pattern is the foundation of event delegation.

Selectors with special characters

IDs and class names can contain characters that mean something in CSS, such as a dot, a colon or a leading digit. document.querySelector("#2024-report") throws, because a CSS id selector can't start with a digit. When you build a selector from a value you don't control, escape it with CSS.escape():

Escaping with CSS.escape()

Other handy entry points

A few properties give you elements without any selector:

  • document.body, document.head, document.documentElement β€” the main structure.
  • document.forms β€” all forms; document.forms.signup finds the form with name="signup" or id="signup".
  • form.elements β€” all fields in a form, by name. You will use it in Working with Forms.
  • document.activeElement β€” the element with keyboard focus.

Choosing a method

You want… Use
One element by id getElementById() or querySelector("#id")
The first match for any selector querySelector()
All matches, as a snapshot querySelectorAll()
To test one element matches()
The nearest matching ancestor closest()
A list that updates itself getElementsByClassName(), children (rarely needed)

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does document.querySelectorAll(".missing") return when nothing matches?

    querySelectorAll() always returns a NodeList, possibly empty. Only querySelector() returns null for no match.
  2. 2. You store const items = list.getElementsByTagName("li") and then append a new <li>. What happens to items.length?

    getElementsByTagName() returns a live collection that always reflects the document. querySelectorAll() would have returned a static snapshot.
  3. 3. Which line gets an array of the text of every .tag element?

    A NodeList has no map(), so spread it into an array first. An HTMLCollection doesn't even have forEach().
  4. 4. A click lands on an <img> inside a <button> inside an <li class="product">. What does event.target.closest(".product") return?

    closest() starts at the element and walks up through its ancestors until one matches the selector.
  5. 5. What is the difference between matches() and querySelector()?

    matches() returns true or false for one element. querySelector() looks down the tree for a matching descendant.

Summary

  • querySelector() returns the first match or null; querySelectorAll() returns a static NodeList, possibly empty.
  • Call them on an element to search only inside it; use :scope to anchor the selector to that element.
  • getElementById() takes a bare id; the getElementsBy… methods and children return live HTMLCollections.
  • Convert lists to arrays with [...list] or Array.from() to use map(), filter() and friends.
  • matches() tests an element against a selector; closest() finds the nearest matching ancestor, including the element itself.
  • Escape untrusted values in selectors with CSS.escape().

Next: Changing Content β€” text, HTML, attributes, dataset and the difference between properties and attributes.