Frontend Master

JavaScript Curriculum

Selecting Elements
+50 XP

Selecting Elements

easy
~25 min·50 XP

The coffee shop menu is in the DOM. Now we need to grab specific elements — the order button, all the price tags, the navigation links — so we can make them interactive.

Selecting Elements

The DOM is a tree of nodes. Your first job is finding the right ones. JavaScript gives you five selection methods — pick the right tool for each situation.

The Five Selection Methods

<selectorplayground></selectorplayground>

💡querySelector is your daily driver
Use querySelector and querySelectorAll for 90% of your selections. They accept any CSS selector — so everything from Chapter 00 works here. getElementById is useful when you have a specific ID and need maximum speed.

Live Query Sandbox

Try selecting different elements from the coffee shop DOM:

live-query.js
document.qsa()
✓ Found 3 elements
[0] <div class="card" data-price="2.50">…</div>
[1] <div class="card" data-price="3.50">…</div>
[2] <div class="card featured" data-price="4.00">…</div>
ℹ️NodeList vs HTMLCollection
querySelectorAll returns a static NodeList — a snapshot that does not update when the DOM changes. getElementsByTagName and getElementsByClassName return a live HTMLCollection that auto-updates. For modern code, always prefer querySelectorAll — it is predictable, flexible, and takes any CSS selector.

Test Your Selector Knowledge

selector-quiz.js1/4
Given this HTML
<div id="app">
  <p class="intro highlight">Welcome</p>
</div>

What's the best way to select: #app p?

⚠️Always check for null
querySelector returns null if nothing matches. Calling .textContent or .style on null throws a TypeError. Always guard: `const el = document.querySelector('.thing'); if (!el) return;` — or use optional chaining: `el?.textContent`.

Your Challenge

Open the coffee shop page. In the console, select the first .card, log its textContent. Then querySelectorAll('.card') and log .length. Then add id="main-nav" to your nav and select it with getElementById.

Challenge

Select the first .card with querySelector and log its textContent. Then use querySelectorAll to select all .card elements and log how many there are. Finally, use getElementById to grab an element by ID and change its textContent.

querySelectorquerySelectorAllgetElementByIdgetElementsByTagNamegetElementsByClassNameNodeListHTMLCollectionnull-checkCSS-selectors
Selecting Elements | Nexus Learn