Skip to the workspace
Pebellslearn by building
DOM APIs  ›  Lesson

Selecting and Reading the DOM

DOM APIs 15 min

javascript / Selecting and Reading the DOM

Explore each scene at your own pace.

01 · Selecting and Reading the DOM

Selecting and Reading the DOM

Selecting and Reading the DOM

The DOM is the browser’s object representation of a document. Selectors find elements, and DOM properties let code read their current content.

JavaScript works with element objects, not with a screenshot of the page.

See the mechanism

Walk through the modelSelecting and Reading the DOMAuthored snapshots of the example; use Run below to test the code.
h2#title"Quiet mornings"
p#resultempty
The browser has created element objects from HTML.
1 of 3

Follow one example

html

querySelector("#title") finds the first matching element or returns null. heading.textContent reads its text, which is copied to the result paragraph. A class selector begins with ., and querySelectorAll produces a collection rather than a single element. The page must contain the element when the lookup runs. This HTML preview supplies a DOM; the console-only JavaScript worker does not.

Predict, change and check

Predict: If the heading id changes but the selector does not, will the lookup still return a heading?

Test your explanation: Change the heading id to article-title without changing the selector. Observe the failure, then repair the selector and check that the displayed copy matches the heading.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

The document is a tree of nodes

A selector searches a document or a chosen subtree; querySelector returns the first matching element or null. Querying before the relevant markup exists can therefore fail even if the selector is spelled correctly. A module script is deferred by its loading semantics, while a classic script's placement also affects timing.

Use querySelectorAll when you need a static list of matches and inspect whether another DOM collection is live before mutating during traversal. An input's current value is often a property, not merely its original HTML attribute. Keep the chosen root explicit so a component does not accidentally select another component's control.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.