Skip to content
dreamcode
dreamcode
Map
DOM basics
Lesson 35 of 48
+15 XP on finish
JS WEB APISChapter 7 · JS Web APIs

Finding and Changing Elements

The DOM (Document Object Model) is a web page as JavaScript sees it: a tree of elements you can read and change. document.querySelector("selector") finds the first element matching a CSS selector, and querySelectorAll finds every match. Change what an element says with .textContent, its look with .classList.add, .remove and .toggle, and its attributes with .setAttribute. The page under the editor is real: run your code and watch it change.

Worked example

How it reads

  • #title selects by id and .status by class, exactly like CSS
  • querySelectorAll returns a list you can index and loop over
  • Changing textContent or classList updates the page immediately
Common mistakes
  • querySelector returns null when nothing matches, so a typo in the selector leads to "Cannot read properties of null".
Cloud tip: Use textContent, not innerHTML, when showing text that came from a user. It can never be run as HTML.
index.js
JAVASCRIPT
real JavaScript, runs in the live page below
preview · index.htmllive page, click around after you run
Console
Run your code to see its output here.
YOUR TURN

Count the li elements and change the status text to 3 planets found (build it from the count), then log the new text.

Press Run to check your work.