The DOM: Selecting & Traversing

Learn how to find and navigate between HTML elements using JavaScript. Master modern query selectors and tree traversal properties.

JavaScript6 min readConcept 41 of 62

Finding Elements

Before your JavaScript can change an element on the screen, it first has to find it inside the massive DOM tree.

Historically, developers used specialized methods like document.getElementById('nav') or document.getElementsByClassName('card').

The Modern Query Engine

Today, we use two universal methods that allow you to find elements using standard CSS selectors:

1. document.querySelector('.card > p') returns the **first** element that matches the CSS selector.

2. document.querySelectorAll('.card') returns a **NodeList** containing *all* elements that match the selector.

Walking the Tree (Traversal)

Sometimes you don't want to search the entire document. If you already have a reference to a specific element, you can "walk" up and down the tree relative to that element.

You can move up using element.parentElement.

You can move down using element.children (all children) or element.firstElementChild.

You can move sideways using element.nextElementSibling or element.previousElementSibling.

The Query Engine

Click the query commands below to run them against the simulated DOM tree. Watch how different selectors and traversal methods light up the exact nodes they target.

The Query Engine Simulator

div#app
<nav>
id="main-nav"
<div>
class="grid"
<div>
class="card"
id="item-1"
<div>
class="card"
id="item-2"
<div>
class="card"
id="item-3"
Click a query to execute
iNotice how querySelector only targets the very first match it finds, while querySelectorAll highlights all three cards. Traversal methods like parentElement let you navigate the tree relative to an origin node!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What does `document.querySelector('.highlight')` return?
  2. 2If you have a `<li>` element and want to find the `<ul>` that contains it, which property should you use?
  3. 3How can you use `.map()` on the result of `document.querySelectorAll('div')`?

Remember this

  • querySelector returns the first matching element.
  • querySelectorAll returns a NodeList of all matching elements.
  • A NodeList is not an Array; use Array.from() to convert it if you need .map().
  • Traverse upwards using parentElement.
  • Traverse sideways using nextElementSibling or previousElementSibling.

Done with this concept?

Mark it complete to track your progress. No login needed.