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

Changing the Page

On this stop
  • textContent
  • classList

You're holding the wire. Selecting an element was step one; every lesson from here uses that same document.querySelector(...) habit as a given. Now flip it.

textContent: replacing what's inside

Once you've selected an element, its textContent property is the text sitting inside it — readable, and writable. Read it on its own and you get back whatever's currently there; assign to it, and you change what's there:

Up closeJavaScript
let statusHeading = document.querySelector("#status");
statusHeading.textContent = "Lamp is on";

That second line doesn't add to what was there — it replaces it completely. Whatever #status used to say, it now says exactly "Lamp is on", the moment that line runs.

classList: flipping a switch CSS already wired

Unit 2 taught you that a class selector like .dark-mode only means something once a CSS rule targets it. JavaScript's job here isn't to style anything itself — it's to flip which classes are present on an element, and let your existing CSS take it from there:

Up closeJavaScript
document.body.classList.add("dark-mode");    // switch it on
document.body.classList.remove("dark-mode"); // switch it off
document.body.classList.toggle("dark-mode"); // flip whichever it currently is

classList is a small toolbox living on every element. .add(...) puts a class on, .remove(...) takes it off, and .toggle(...) does whichever one the element currently isn't — on if it was off, off if it was on.

Common mistake

.toggle(...) flips whatever state is already there — it doesn't know "on" from "off," only "the opposite of right now." Call it twice by accident (a common one once lesson 8 has you responding to clicks), and you're back exactly where you started, having visibly done nothing. If you need a guaranteed direction no matter what state you're in, reach for .add(...) or .remove(...) instead of .toggle(...).

You can now read and rewrite an element's text, and flip its classes on and off. Both of today's tools change the page the instant they run — which is exactly the gap left to close. The only thing missing is a reason for any of this to run besides the page just loading — and that's exactly what's next.

There's a lamp panel in the lab that needs flipping.