Skip to the workspace
Pebellslearn by building
JavaScript  ›  Lesson

The DOM — Changing the Page

JavaScript 14 minScripts find elements in the DOM with querySelector or querySelectorAll using CSS selectors, then change their text, classes and attributes or add new elements.

frontend / The DOM — Changing the Page

Explore each scene at your own pace.

01 · The rule

The rule

The DOM — Changing the Page

The bakery's rye sells out by noon. Instead of editing the HTML file each day, a script should mark it "Sold out" on the page. In the browser lesson you met the DOM, the tree the browser builds from your HTML. JavaScript changes what visitors see by changing that tree.

The rule

Find the element, then change it.

Finding elements. The document object is your way into the tree. Two methods cover most needs, and both take a CSS selector, so everything from the CSS section carries over:

const heading = document.querySelector("h1");          // first match, or null
const rye = document.querySelector("#rye");
const cards = document.querySelectorAll(".card");       // every match
  • querySelector returns the first matching element, or null if nothing matches.
  • querySelectorAll returns a NodeList of every match, which you can loop over with for...of or forEach. If nothing matches, the list is empty.

Changing elements. Once you hold an element, you can change it:

rye.querySelector(".status").textContent = "Sold out";
rye.classList.add("sold-out");
rye.querySelector("button").disabled = true;
  • textContent reads or replaces the text inside an element.
  • classList.add, remove and toggle switch classes, so CSS stays in charge of the looks.
  • Attributes and properties such as disabled, src and href can be set directly.

Creating elements. Build a new node, fill it, then attach it:

const item = document.createElement("li");
item.textContent = "Rye loaf × 1";
document.querySelector("#basket").append(item);

A word on innerHTML: it replaces an element's contents with a string parsed as HTML. It is handy for trusted markup, but if any part of that string came from a user (a name typed into a form, say), a crafted value can inject a script into your page. For text, use textContent, which never interprets HTML.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.