Selecting & Traversing the DOM

Advanced · 18 min read · ▶ live playground · ✦ checkpoint

The DOM can hold thousands of elements, but your code usually needs one exact thing: the selected player, the current song, the button inside this card. Selecting and traversing the DOM means turning "that thing over there" into a precise object your JavaScript can use.

Select by asking a precise question

A CSS selector is a pattern like .featured or #checkout that describes which elements you want. The surprise is that JavaScript uses the same selector language CSS uses, so selector strings become your DOM API, the set of commands your code hands to the page.

Think of a selector as a mailing address for elements: broad enough to find a group, specific enough to find one house when you need it.

  • document.querySelector(selector) returns the first matching element, or null when nothing matches.
  • document.querySelectorAll(selector) returns every matching element as a static NodeList, a list-like DOM collection that does not update itself after the query runs.
  • You can call querySelector on document for the whole page, or on an element to search inside that element only.

Run this, then change .player-card.featured to .player-card and watch how "first match" works.

web page — live previewsandboxed
Run rebuilds the page

featuredCard is one element. playerCards is a collection. retiredCard is null, the intentionally empty value you met earlier, because no element matches that selector. In real code, any query that might miss needs an if (result !== null) check before you use it.

Walk from the element you have

Traversal is moving from one DOM element to related elements instead of starting over at document. It keeps your code local: if you already have a button, search around that button.

Two methods make that feel exact:

  • element.matches(selector) asks, "does this element itself fit this selector?"
  • element.closest(selector) walks upward through ancestors, the parent, grandparent, and anything above, until it finds a match or returns null.

This is the difference between searching the whole building and walking from the room you are already standing in.

web page — live previewsandboxed
Run rebuilds the page

Notice the second line: the button does not match .featured, even though it sits inside the featured card. matches checks only the element you call it on. closest is the method that climbs.

This pattern becomes huge when events arrive in Section 15. A click often gives you the tiny element the user touched; closest lets you find the useful card, row, or form around it.

Move through the DOM family

The DOM tree uses family words because the shape really is a tree. A parent is the element directly above another element, a child is directly inside it, and siblings share the same parent.

For beginner DOM work, reach for the element-only properties:

  • parentElement moves up one level.
  • children gives the element's direct child elements.
  • firstElementChild and lastElementChild pick the ends.
  • previousElementSibling and nextElementSibling move sideways.

Those names skip the whitespace text between tags, which is usually what you want when you are thinking in visible elements.

web page — live previewsandboxed
Run rebuilds the page

The last few lines are there to force the tree to change. You do not need to memorize the create-and-append code yet; that is the next lesson.

The selection lesson is the collection lesson, though. A static collection is a snapshot: querySelectorAll(".song") stays at 3 after the new song appears. A live collection is a moving view: playlist.children updates to 4 because it points at the element's current children.

That difference explains a lot of strange bugs. If you loop over a live collection while changing the children, the list can shift under your feet. When you want a stable list, querySelectorAll is usually the calmer default.

Check your selector shape

When a selector fails, do not guess. Ask three questions in order:

  1. Does the selector mean what I think it means in CSS?
  2. Am I searching from the right starting point, document or a smaller element?
  3. Can this query legally return null, and did I handle that case?

The best DOM code reads like intent: find the current card, climb to its container, then look inside that container for the piece you need.

Next, you will change the tree on purpose: create elements, replace words safely, and remove the pieces the page no longer needs.

Checkpoint

Answer all three to mark this lesson complete

+50 XP on completion