Show contents
Chapter 3 of 6 · 20 min
The DOM: reading and changing the page
By the end of this chapter, you'll be able to
- Explain what the DOM is and how it's built from the HTML
- Select elements with querySelector and querySelectorAll
- Change an element's text, attributes and classes
- Create new elements and insert them into the page
The DOM, a tree of objects
When the browser reads the HTML, it builds the DOM (Document Object Model): a tree where each tag becomes a node, an object with properties and methods. The document object is the root of this tree. Changing the DOM immediately changes what's displayed.
The browser automatically redraws the page: the new text appears.
Text description of the animation
- The browser receives the HTML.
- It builds the DOM: the paragraph becomes an object, reachable from document.
- The page is displayed from the DOM.
- The script selects the paragraph and changes its text. The HTML file itself doesn't change.
- The browser automatically redraws the page: the new text appears.
Selecting elements
You find an element with a CSS selector, exactly as in a style sheet:
const heading = document.querySelector("h1"); // the first h1
const score = document.querySelector("#score"); // the element with id "score"
const cards = document.querySelectorAll(".card"); // every element with the class "card"
console.log(cards.length);
cards.forEach((card) => console.log(card.textContent));
querySelectorreturns the first matching element, ornullif there's none;querySelectorAllreturns a list of all the elements, which you go through withforEachorfor…of.
Changing an element
const message = document.querySelector("#message");
message.textContent = "Sign-up saved!"; // the text
message.classList.add("success"); // adds a CSS class
message.classList.remove("hidden"); // removes a class
message.classList.toggle("open"); // adds or removes depending on the case
message.setAttribute("role", "status"); // any attribute
const link = document.querySelector("a.help");
link.href = "/help"; // common attributes are also properties
Change the appearance by adding or removing classes, and let the CSS decide the style. It's clearer than changing element.style.color in the code, and the styling stays in one place.
Creating elements
const list = document.querySelector("#tasks");
const item = document.createElement("li"); // creates an <li> that isn't in the page yet
item.textContent = "Water the vegetable patch";
item.classList.add("task");
list.append(item); // adds it at the end of the list
list.querySelector("li").remove(); // removes the first <li>
An element created with createElement only appears once inserted with append (at the end), prepend (at the start) or before / after (next to another element).
Your turn
This lab really runs your JavaScript in an isolated page. The console.log messages and errors appear below the preview.
The scoreboardHTML · CSS · JS
Preview
Console
(Nothing in the console yet.)Your code runs in an isolated page, with no access to this site or the Internet · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Worked exercise: the character counter
A page contains a paragraph <p id="post"> and a counter <span id="counter">. Write the JavaScript that displays in the counter the number of characters of the paragraph out of a maximum of 280, for example 42 / 280, and adds the class too-long to the counter if the text is longer than 280 characters.
Hint 1
document.querySelector("#post").textContent.length gives the number of characters.Hint 2
classList.toggle("too-long", condition) adds the class if the condition is true and removes it otherwise.Show the solution and common mistakes
const post = document.querySelector("#post");
const counter = document.querySelector("#counter");
const length = post.textContent.trim().length;
counter.textContent = `${length} / 280`;
counter.classList.toggle("too-long", length > 280);
trim() removes spaces and line breaks at the start and end, which HTML often adds just from the way the code is laid out.
Common mistakes:
- Writing
querySelector("post")without the#: the selector looks for a<post>tag, returnsnull, and the next line raisesTypeError: Cannot read properties of null. - Running the script before the element exists (a
<script>placed in the<head>): samenullerror. Put the script at the end of<body>, or use<script defer>.
Summary
- 1The DOM is the tree of objects built from the HTML; changing it changes the display.
- 2querySelector finds the first element, querySelectorAll finds them all.
- 3textContent, classList and attributes let you change an element.
- 4createElement then append add an element to the page.
- 5Never innerHTML with typed data: it opens the door to XSS vulnerabilities.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.