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.
The shortcut
Say every DOM task as two verbs: "find ___, then ___ it." The first half becomes a querySelector with a CSS selector. The second half becomes a property or method: text, class, attribute, or append.
Find
"Find the card with id rye":
document.querySelector("#rye").
The trap is running this script before the HTML has been parsed. querySelector then finds nothing and returns null. Loading scripts with defer avoids it.
Drills
Answer fast — trust the rule.
The page has five .card elements. What does document.querySelector(".card") return?
What does document.querySelector("#croissant") return when no element has that id?
A customer types their name, which the page shows in a greeting. Which is the safe choice?
What is the best way to make a sold-out card look grey?
Remember
- Find the element, then change it.
- Say it as "find ___, then ___ it": a selector, then a property or method.
- Trap:
querySelectorreturnsnullwhen nothing matches; usetextContent, notinnerHTML, for user text.
