Lesson 9 / 1090%

Lesson 9

Manipulate the DOM

28 min

querySelector, textContent, classList : modify a page in real-time.

What is the DOM?

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.

The DOM tree

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:

simple-page.html
<body>
  <h1>Hello</h1>
  <p>A <a href="#">link</a>.</p>
</body>
dom-tree.txt
body
├── h1
│   └── "Hello"       (text node)
└── p
    ├── "A "          (text node)
    ├── a
    │   └── "link"    (text node)
    └── "."           (text node)
  • Tags are element nodes; the text they contain forms text nodes.
  • The <body> is the parent of the <h1> and the <p>, which are siblings.
  • The 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.

The window and document objects

In 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.

window-and-document.js
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 page

Since window is the global object, it can be omitted: you write document and not window.document.

Selecting a DOM element

The most commonly used method to select an element isquerySelector, which accepts anyCSS selector (tag, class, id...).

selection.js
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 found
  • querySelector 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.
loop-through-elements.js
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#.

check-null.js
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";
}

Modifying the content of an element

content-modification.js
const title = document.querySelector("h1");

title.textContent = "New title!";                  // modifies only the text
title.innerHTML = "New <strong>title</strong>!";   // also modifies the HTML
  • textContent 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.
xss-vulnerability.js
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 interpreted

Reading and modifying attributes

HTML attributes (href, src, alt,disabled...) are handled with dedicated methods or directly as properties of the element.

attributes.js
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)

Modifying styles and CSS classes

style-and-classes.js
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 false

It 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).

Creating and inserting new elements

element-creation.js
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 list

A created element only appears on the page once it isinserted into the DOM. There are several insertion methods:

insertion-methods.js
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" element

To 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.

document-fragment.js
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 page

To remove an element from the DOM:

element-removal.js
const item = document.querySelector(".item");
item.remove(); // removes the element from the page

Navigating between elements: parent, children, siblings

dom-navigation.js
const 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");

Reacting to user actions: events

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.

click-event.js
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
});
  • Common events are click, input (typing in a field), submit, keydown and mouseover.
  • preventDefault cancels the native behavior (submitting a form, following a link).
  • Values read from a field with 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.

delegation.js
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");
});

The right time to run your script

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.

index.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:

dom-content-loaded.js
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:

  1. Select both elements with querySelector.
  2. Change the text of the paragraph to "The DOM is magic!" with textContent.
  3. Add an "active" class to the paragraph with classList.add.
  4. Dynamically create a new <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:

  1. On each click of the button, increment a variable counter and update the text of the paragraph.
  2. When the counter exceeds 10, add the "record" class to the paragraph.
  3. Add a "Reset" button that sets the counter back to zero and removes the "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:

  1. Intercept the submit event and call preventDefault.
  2. Read the value of the field, remove the spaces with trim() and reject empty entries.
  3. Create an <li> with the entered first name and add it to the list with append.
  4. Add a "Remove" button in each <li> that deletes the guest, using event delegation and closest.

Key takeaways

  • The DOM is the representation of an HTML page that JavaScript can read and modify.
  • The DOM is a tree of nodes built by the browser: it is not the HTML file itself.
  • querySelector and querySelectorAll let you select elements with a CSS selector.
  • Prefer textContent and classList over innerHTML and style whenever possible.
  • Create an element with createElement, then insert it with append, prepend, before or after.
  • React to user actions with addEventListener, and use delegation for lists.
  • Make sure the DOM is loaded before manipulating the page (defer or DOMContentLoaded).