E-Learning Platform
0 of 139 builtAlways freeSign in
← Web Foundation I
3.06

Selecting DOM Elements

On this stop
  • The DOM
  • querySelector

Every line of JavaScript you've written so far has stayed inside its own script, never touching the page sitting right next to it. That changes now.

The DOM: a live wiring diagram of the page

When the browser reads your HTML, it doesn't just paint it and forget the instructions — it builds a live, in-memory model of every element, called the DOM (Document Object Model). Think of it as the actual wiring panel behind the page you see: your HTML file is the blueprint, but the DOM is the real, physical panel the browser assembled from it — and unlike the blueprint, JavaScript can reach into the panel and read or change it while the page is running.

document.querySelector: reaching for one wire

Up closeJavaScript
let heading = document.querySelector("h1");

document is your entry point — it stands for the whole live page. .querySelector(...) searches the DOM for the first element matching whatever you hand it, using the exact same selector syntax CSS uses: a tag name ("h1"), a class with a dot (".tagline"), an id with a hash ("#main-heading"). heading now holds a reference to that real, on-page element — not a copy, the actual thing — ready for the next lesson to change.

If nothing on the page matches your selector, querySelector doesn't error — it quietly hands back null, JavaScript's "nothing here" value.

Common mistake

The selector is always a string, in quotes — document.querySelector(h1) (no quotes) looks for a variable named h1, not the tag, and throws a reference error. And a typo in the selector doesn't announce itself: you get null back, silently, and the error only shows up later, when you try to do something with an element that isn't actually there. If a later line complains it "cannot read properties of null," a mismatched selector is almost always the reason.

You can now reach into the real page from your script and grab hold of one exact element. Next lesson: what you're actually allowed to do with it once you're holding it.

Quick quiz

Quick check: the DOM

No score kept — pick again as often as you like
  1. 1. You load a page. What is the DOM?
  2. 2. Your script changes an element through the DOM — no file is saved. What does the original HTML file look like afterward?
Pick an answer for every question.

Then the lab: two real elements to take hold of.