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 matchquerySelectorreturns the first matching element, ornullif nothing matches.querySelectorAllreturns a NodeList of every match, which you can loop over withfor...oforforEach. 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;textContentreads or replaces the text inside an element.classList.add,removeandtoggleswitch classes, so CSS stays in charge of the looks.- Attributes and properties such as
disabled,srcandhrefcan 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.