JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 11: The Document Object ModelLesson 52 of 150About 40 minutes

Lesson 52: Selecting elements

01Opening question

A page has hundreds of elements. How does your code find exactly the price, the button or the list it needs?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

querySelector takes a CSS selector and returns the first match; querySelectorAll returns all matches.

const intro = document.querySelector("#intro");
console.log(intro.textContent);
const items = document.querySelectorAll(".item");
console.log(items.length);

03Objective and prerequisites

Learning objective: Select elements with getElementById, querySelector and querySelectorAll using CSS selectors, handle missing elements, and search inside a container.

You need: Lesson 51: Understanding the DOM tree

Skills practised: The DOM, Selecting elements.

04Explanation

document.getElementById("total") finds the element with id="total". Note: no # here.

document.querySelector(selector) accepts any CSS selector (#id, .class, tag, [attr]) and returns the first match, or null.

document.querySelectorAll(selector) returns a NodeList of every match. It has length and forEach, and you can spread it into an array.

Call querySelector on an element instead of document to search only inside that element.

05Definitions

Selector
A CSS pattern such as #id, .class or tag that matches elements.
querySelector
Returns the first element matching a selector, or null.
querySelectorAll
Returns a static NodeList of all elements matching a selector.
NodeList
A list-like collection of nodes with length and forEach.

Open the full glossary

06Visual learning object

CSS selector explorer. Type a selector and see exactly which elements in the HTML it matches, in document order.

Loading the interactive object…

Open the full CSS selector explorer page with its guided experiment.

07Examples

ex-052-01Three kinds of selector Browser page (sandboxed preview)

Ids use #, classes use ., attributes use [ ].

console.log(document.querySelector("#intro").textContent);
console.log(document.querySelector(".active").textContent);
console.log(document.querySelector('a[href="/shop"]').textContent);
console.log(document.getElementById("intro") === document.querySelector("#intro"));
Sample input
None
Expected output
Welcome back Home Shop true
Common mistake
Writing getElementById("#intro"); getElementById takes the bare id.
Try this
Select the first a element with the tag selector.
Source
examples/ex-052-01-selectors.js

ex-052-02Every match Browser page (sandboxed preview)

querySelectorAll returns all matching elements.

const items = document.querySelectorAll(".item");
console.log(items.length);
items.forEach((li) => console.log(li.textContent));
console.log(document.querySelectorAll(".sold-out").length);
Sample input
None
Expected output
3 Tea Cake Juice 1
Common mistake
Using querySelector and getting only the first match.
Try this
Select only the items that are not sold out with .item:not(.sold-out).
Source
examples/ex-052-02-all-matches.js

ex-052-03When nothing matches Browser page (sandboxed preview)

A selector with no match gives null.

const banner = document.querySelector("#banner");
console.log(banner);
console.log(banner?.textContent ?? "no banner on this page");
console.log(document.querySelectorAll(".none").length);
Sample input
None
Expected output
null no banner on this page 0
Common mistake
Calling banner.textContent without checking, which throws a TypeError.
Try this
Add a banner element and run again.
Source
examples/ex-052-03-missing.js

ex-052-04Search inside a container Browser page (sandboxed preview)

Calling querySelector on an element searches only inside it.

const card = document.querySelector("#card-2");
console.log(card.querySelector(".price").textContent);
console.log(document.querySelector(".price").textContent);
Sample input
None
Expected output
$30 $8
Common mistake
Searching the whole document and getting the first card's price.
Try this
Loop over every .card and print its name and price.
Source
examples/ex-052-04-scoped.js

ex-052-05NodeList to array Browser page (sandboxed preview)

Spreading a NodeList unlocks map, filter and reduce.

const prices = [...document.querySelectorAll(".price")].map((el) => Number(el.textContent));
console.log(prices);
console.log(prices.reduce((a, b) => a + b, 0));
Sample input
None
Expected output
[12, 5.5, 20] 37.5
Common mistake
Calling map directly on a NodeList, which does not have map.
Try this
Print only the prices above 10.
Source
examples/ex-052-05-to-array.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the selector

Use the right selector syntax for an id.

const total = document.querySelector("total");
console.log("Total: " + total.textContent);

Sum the prices

Collect values from every matching element.

// TODO: select every .price, add up the numbers and print "Sum: 35"

Query helpers

Write reusable selection helpers with scoped searches.

// Write textsOf(selector, root = document) and countIn(sectionId, selector)

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: <p class="x">A</p><p class="x">B</p>
console.log(document.querySelector(".x").textContent);
console.log(document.querySelectorAll(".x").length);

What is printed?

10Debugging investigation

The sale discount crashes the page

The sale script should take 10% off every price, but it stops with a TypeError and no price changes.

const prices = document.querySelector(".price");
prices.forEach((el) => {
  el.textContent = (Number(el.textContent) * 0.9).toFixed(2);
});
console.log([...document.querySelectorAll(".price")].map((el) => el.textContent).join(", "));

More cases in the Debugging Detective Laboratory

11Practical scenario

Updating every price

A sale banner applies a discount to every price on a product page. The script selects all price elements with one selector, reads each value and writes the new price back, so adding a product to the page needs no script change.

// document.querySelectorAll("[data-price]").forEach((el) => {
//   el.textContent = (Number(el.dataset.price) * 0.9).toFixed(2);
// });
console.log("One selector updates every price");

12Knowledge check

1. What does querySelector return when nothing matches?

  • undefined
  • null
  • An empty NodeList
  • It throws

2. Which selects the element with id="cart"?

  • document.querySelector("cart")
  • document.getElementById("#cart")
  • document.querySelector("#cart")
  • document.querySelector(".cart")

3. Why does this throw TypeError: buttons.map is not a function?

const buttons = document.querySelectorAll("button");
buttons.map((b) => b.textContent);
  • NodeList has no map; spread it into an array first
  • There are no buttons
  • map needs two arguments
  • querySelectorAll returns null

4. For two .card elements each with one .price inside, what is printed?

const first = document.querySelector(".card");
console.log(first.querySelectorAll(".price").length);
  • 1
  • 2
  • 0
  • An error

5. Which selector matches buttons with a data-action attribute?

  • button.data-action
  • button[data-action]
  • button#data-action
  • data-action button

6. Which is the more stable hook for a script to find a delete button?

  • button.red.small
  • [data-action="delete"]
  • div > div > button:nth-child(3)
  • button:last-child

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the selector: Prints the total
  • Sum the prices: Prints Sum: 35; Uses querySelectorAll
  • Query helpers: Prints texts and count; Scoped texts; Missing section

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-11-the-document-object-model/lesson-052-selecting-elements/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • getElementById takes a bare id; querySelector takes any CSS selector.
  • querySelector returns the first match or null.
  • querySelectorAll returns a NodeList of all matches.
  • Search inside a container to keep queries local.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation selecting DOM elements
Context: I am learning selecting DOM elements in JavaScript.
Task: Explain getElementById, querySelector and querySelectorAll with id, class and attribute selectors.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction selecting DOM elements drill
Context: I have practised selecting DOM elements.
Task: Give me six HTML snippets with selector code and ask what each prints, including null cases.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging selecting DOM elements bug
Context: My querySelector call returns null even though the element is on the page.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation selecting DOM elements practice
Context: I finished the selecting DOM elements exercises.
Task: Create three exercises that select and summarise elements on a product page.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review selecting DOM elements review
Context: Here is my code that uses selecting DOM elements.
Task: Review my selectors for fragility and missing-element handling.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.