What is the DOM?
The Document Object Model is a programmable representation of an HTML or XML document in a hierarchical tree structure. Every element on a webpage (whether it’s a <p> paragraph, an <h1> heading, or a <div> container) is represented in the DOM as a node.
When a browser loads a webpage, it creates a DOM from the HTML code. This model serves as an interface between the structure of a webpage (HTML), its design (CSS), and its interactive logic (JavaScript).
Why is the DOM important?
The DOM makes dynamic websites possible. Its main advantages are:
- Interactivity: Changes can be made in real time without having to reload the entire page.
- Flexibility: Developers can add, remove, or modify content.
- Accessibility: Screen readers and other assistive technologies use the DOM to make websites accessible to all users.
- Standardisation: The DOM is a web standard, today maintained by the WHATWG as a Living Standard, that is supported in all modern browsers.
DOM tree and its structure
The DOM represents a webpage as a tree structure, where each element is a node:
- The root node:
documentis the top level, with the root element<html>below it. - Parent and child nodes: HTML elements can contain other elements (e.g. a
<ul>contains<li>elements). - Text nodes: Every piece of visible text is a separate node.
Here is a visual representation:
document └── html ├── head └── body ├── h1 ├── p └── div └── ul ├── li └── li
DOM interaction with JavaScript
The DOM allows JavaScript to access HTML elements to modify content. Some important methods are:
document.getElementById("demo"): Accesses an element with a specific ID.document.getElementsByClassName("example"): Selects elements by their CSS class.document.querySelector("p"): Selects the first<p>element.
Here is an example of how JavaScript can change the text of a paragraph:
document.getElementById("demo").textContent = "New Text!";
DOM manipulation: adding and removing content
With the DOM, you can dynamically create new elements and add them to the page:
Adding an element
let newElement = document.createElement("p");
newElement.textContent = "This is a new element!";
document.body.appendChild(newElement);
Removing an element
let elementToRemove = document.getElementById("demo");
elementToRemove.remove();
DOM events: responding to user actions
The DOM responds to user interactions through events. An example is clicking a button:
document.getElementById("myButton").addEventListener("click", function() {
alert("Button was clicked!");
});
DOM optimisation and best practices
DOM manipulations can be costly in terms of performance, so some best practices should be observed:
- Minimise DOM access: Every access to the DOM can incur performance costs.
- Use document fragments: collect several changes in a fragment and insert them into the DOM in one step.
- Change styles via CSS classes: Switching a class bundles several style changes into one step and keeps styling in the stylesheet.
