The DOM: Selecting & Traversing
Learn how to find and navigate between HTML elements using JavaScript. Master modern query selectors and tree traversal properties.
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
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
querySelectorreturns the first matching element.querySelectorAllreturns 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
nextElementSiblingorpreviousElementSibling.
Done with this concept?
Mark it complete to track your progress. No login needed.