Lesson 9
28 min
querySelector, textContent, classList : modify a page in real-time.
Definition
The DOM (Document Object Model) is a programming interface (API) provided by the browser, which represents an HTML document as a tree of objects that JavaScript can read, traverse and modify.
The DOM (Document Object Model) is the representation of an HTML page as a tree of objects that JavaScript can read and modify. Every HTML tag (<h1>,<p>, <div>...) becomes anode of this tree, accessible and manipulable from a script. This is the mechanism that makes it possible to modify a pageafter it has been loaded by the browser, without having to reload it: it is the basis of all interactivity on the web.
The DOM is not the HTML file itself: HTML is simple text, which the browser parses to build a structure of objects in memory. Modifying the DOM changes the displayed page, but not the HTML file that remains on the server.
Imagine a family tree: each element has a parent, may have children, and siblings (the elements that share the same parent). Here is a minimal piece of HTML and the corresponding tree:
<body>
<h1>Hello</h1>
<p>A <a href="#">link</a>.</p>
</body>body
├── h1
│ └── "Hello" (text node)
└── p
├── "A " (text node)
├── a
│ └── "link" (text node)
└── "." (text node)<body> is the parent of the <h1> and the <p>, which are siblings.document object is the root of the tree and the entry point for any manipulation.In practice, you will mostly work with elements. Modern properties such as children ornextElementSibling conveniently ignore text nodes and comments, which simplifies the work.
window and document objectsIn a browser, two global objects are always available:window represents the browser window (the tab), anddocument represents the HTML page loaded in that window. It is document that gives access to the DOM tree.
console.log(document.title); // the title of the page
console.log(document.body); // the <body> element
console.log(window.innerWidth); // width of the window in pixels
console.log(window.location.href); // address of the pageSince window is the global object, it can be omitted: you write document and not window.document.
The most commonly used method to select an element isquerySelector, which accepts anyCSS selector (tag, class, id...).
const title = document.querySelector("h1"); // by tag
const button = document.querySelector("#my-button"); // by id
const card = document.querySelector(".card"); // by class
// querySelectorAll returns ALL the matching elements (a list)
const buttons = document.querySelectorAll(".btn");
console.log(buttons.length); // number of buttons foundquerySelector only returns the first element found, or null if none matches.querySelectorAll returns a list (NodeList) of all the matching elements, which you can loop through with forEach.const buttons = document.querySelectorAll(".btn");
buttons.forEach((button) => {
console.log(button.textContent);
});Since the syntax is that of CSS, every selector works:"nav a", "ul > li", 'input[type="email"]',"li:first-child"... You can also call querySelectoron an element to search only inside it. Finally,getElementById("my-button") is an older method, still valid, which takes the id without the#.
const card = document.querySelector(".card");
const title = card.querySelector("h2"); // searches only inside the card
// If the element does not exist, title is null: we check before using it
if (title) {
title.textContent = "Hello";
}const title = document.querySelector("h1");
title.textContent = "New title!"; // modifies only the text
title.innerHTML = "New <strong>title</strong>!"; // also modifies the HTMLtextContent is to be preferred in the vast majority of cases: it is safer and faster.innerHTML lets you insert HTML, but exposes you to security risks (code injection) if the content comes from an untrusted source, such as user input.const zone = document.querySelector("#zone");
const input = '<img src="x" onerror="alert(1)">'; // malicious input
zone.innerHTML = input; // DANGEROUS: the code runs in the page
zone.textContent = input; // SAFE: displayed as is, without being interpretedHTML attributes (href, src, alt,disabled...) are handled with dedicated methods or directly as properties of the element.
const link = document.querySelector("a");
link.getAttribute("href"); // read
link.setAttribute("href", "https://example.com"); // modify or create
link.hasAttribute("target"); // true or false
link.removeAttribute("target"); // remove
// Boolean attributes: we use properties
document.querySelector("button").disabled = true;
document.querySelector("input").checked = true;
// Custom data-* attributes: <button data-product-id="42">
const button = document.querySelector("button");
console.log(button.dataset.productId); // "42" (always a string)const title = document.querySelector("h1");
// Modify a CSS property directly (use sparingly)
title.style.color = "indigo";
title.style.fontSize = "2rem";
// Manipulate CSS classes (the preferred approach)
title.classList.add("active"); // adds a class
title.classList.remove("hidden"); // removes a class
title.classList.toggle("visible"); // adds the class if absent, removes it if present
title.classList.contains("active"); // true or falseIt is generally preferable to manipulate CSS classesrather than inline styles (style.xxx): this keeps the style in the CSS files and the behavior in the JavaScript, which makes the code easier to maintain.
In style, properties are written in camelCase(backgroundColor for background-color) and values are strings with their unit ("16px"). To read the style actually applied, including the one coming from CSS stylesheets, use getComputedStyle(element).
const list = document.querySelector("ul");
const newItem = document.createElement("li");
newItem.textContent = "New element";
newItem.classList.add("item");
list.appendChild(newItem); // adds the element at the end of the listA created element only appears on the page once it isinserted into the DOM. There are several insertion methods:
list.append(newItem); // at the end, inside the list
list.prepend(newItem); // at the start, inside the list
reference.before(newItem); // just before the "reference" element
reference.after(newItem); // just after the "reference" elementTo insert many elements, first assemble them in aDocumentFragment (an invisible container) then insert it in one go: this saves the browser from recalculating the page on every addition.
const fruits = ["Apple", "Banana", "Cherry"];
const fragment = document.createDocumentFragment();
fruits.forEach((name) => {
const li = document.createElement("li");
li.textContent = name;
fragment.append(li);
});
list.append(fragment); // a single insertion into the pageTo remove an element from the DOM:
const item = document.querySelector(".item");
item.remove(); // removes the element from the pageconst item = document.querySelector(".item");
item.parentElement; // the parent element
item.children; // the direct child elements
item.nextElementSibling; // the next element at the same level
item.previousElementSibling; // the previous element at the same level
// closest walks up the ancestors until it finds a matching selector
item.closest(".card");Modifying the DOM really makes sense when the page reacts to a click, an input or the submission of a form. We listen for theseevents with addEventListener, which takes the event type and a function executed on each occurrence.
const button = document.querySelector("#change");
const message = document.querySelector("#message");
button.addEventListener("click", (event) => {
message.textContent = "You clicked!";
console.log(event.target); // the element that triggered the event
});
const form = document.querySelector("form");
form.addEventListener("submit", (event) => {
event.preventDefault(); // prevents the page from reloading
});click, input (typing in a field), submit, keydown and mouseover.preventDefault cancels the native behavior (submitting a form, following a link).value are always strings: convert them with Number() if needed.For a list with many elements, or elements created dynamically, we useevent delegation: a single listener on the parent, which identifies the originating element thanks toevent.target.
const list = document.querySelector("ul");
list.addEventListener("click", (event) => {
const item = event.target.closest("li");
if (!item) return; // the click was not on an item
item.classList.toggle("done");
});A script that runs too early may try to select elements that do not exist yet in the DOM, because the browser has not finished reading the HTML.
<!-- Solution 1: the "defer" attribute -->
<script src="script.js" defer></script>
<!-- Solution 2: place the script just before the closing body tag -->
<body>
<!-- ... page content ... -->
<script src="script.js"></script>
</body>You can also explicitly wait for the DOM to be ready:
document.addEventListener("DOMContentLoaded", () => {
console.log("The DOM is ready, we can safely manipulate the page.");
});defer runs the script after the DOM has been built, respecting the order of the scripts, whereasasync runs it as soon as it is downloaded, with no guarantee: to manipulate the DOM, choosedefer.
Practical exercise
Create an HTML page containing a <p id="message">and a button <button id="change">. In JavaScript:
querySelector."The DOM is magic!" with textContent."active" class to the paragraph with classList.add.<li> element and add it to an existing list on the page.Exercise 2: a click counter
Create a page with a button and a paragraph displaying "Clicks: 0". In JavaScript:
counter and update the text of the paragraph.10, add the "record" class to the paragraph."record" class.Exercise 3: a guest list
Create a form with a field for a first name and a list<ul id="guests">. In JavaScript:
submit event and call preventDefault.trim() and reject empty entries.<li> with the entered first name and add it to the list with append.<li> that deletes the guest, using event delegation and closest.querySelector and querySelectorAll let you select elements with a CSS selector.textContent and classList over innerHTML and style whenever possible.createElement, then insert it with append, prepend, before or after.addEventListener, and use delegation for lists.defer or DOMContentLoaded).