What is the Document Object Model (DOM)?
By Alex Carter on October 2, 2024
Web pages are more than just static content displayed in a browser. They can be modified, updated, and interacted with using scripts. The structure of a page, including its elements and content, can be accessed and manipulated through a standardized interface. This allows developers to create dynamic web experiences, from simple text changes to complex user interactions. Understanding how this works is essential for effective web development.
What is the DOM?
The Document Object Model (DOM) is a programming interface for web documents that allows scripts to dynamically modify a page’s structure, style, and content. It represents the document as a hierarchy of nodes and objects, enabling programming languages to interact with and manipulate the page.
A web page exists as both a visible document in the browser and as an underlying HTML source. The DOM provides an interactive representation of the page, making it accessible for modification through scripting languages like JavaScript. The DOM structures the web page elements into objects, such as the document object representing the entire page or the HTMLTableElement interface for handling tables.
Built on multiple APIs, the DOM is designed to be extensible. The core DOM defines the fundamental structure, while additional APIs introduce new functionalities. For example, the HTML DOM API supports HTML document manipulation, while the SVG API provides capabilities for handling SVG graphics.
What is the HTML DOM?
The HTML Document Object Model (DOM) is a structured representation of HTML documents that allows programs to interact with web pages. It establishes:
- HTML elements as objects;
- Properties associated with each HTML element;
- Methods for accessing and modifying elements;
- Events that can trigger actions on elements.
Simply put, the HTML DOM provides a standardized way to retrieve, modify, add, or remove elements from a web page.
Understanding the HTML DOM is essential for modifying web pages, and using CSS techniques for cross-browser compatibility helps ensure consistent styling across browsers.
How DOM Works with JavaScript
Most interactions with the DOM are done using JavaScript. While JavaScript is a programming language, the DOM itself is not—it functions as an interface that allows JavaScript to interact with web pages, HTML documents, SVG elements, and their components. Through the DOM, JavaScript can access and manipulate various elements like the document structure, tables, headings, and text content.
Though often used together, the DOM is not part of JavaScript but a Web API designed for webpage manipulation. JavaScript can also run outside of a browser, such as in Node.js, which uses different APIs and does not include the DOM by default.
The DOM is designed to be language-independent, providing a standardized way to represent and modify documents. While JavaScript is the most common way to interact with the DOM, other languages, such as Python, can also work with it.
How to Interact with the DOM
Accessing the DOM requires no special setup—you can start using it directly in JavaScript within a script executed by the browser. Scripts can be embedded within a <script> tag inside an HTML document or linked externally.
When a script runs, it can interact with the document using the DOM API. This allows modifications to elements, attributes, and content on the page. For example, the following inline script logs a message to the console when the page loads:
<body onload=”console.log(‘Welcome to my home page!’);”>
…
</body>
However, separating HTML structure from JavaScript is considered best practice. JavaScript is typically kept in a dedicated script section or an external file.
The following example demonstrates how JavaScript dynamically creates an <h1> element, adds text to it, and appends it to the document when the page loads:
<html lang=”en”>
<head>
<script>
// Execute this function once the page has fully loaded
window.onload = () => {
// Create a new h1 element
const heading = document.createElement(“h1”);
const headingText = document.createTextNode(“Big Head!”);
heading.appendChild(headingText);
// Add the new element to the page
document.body.appendChild(heading);
};
</script>
</head>
<body></body>
</html>
By using the DOM, JavaScript can dynamically modify web pages, making them more interactive and responsive.
Basic Data Types in the DOM
Different object types are passed through the API, and understanding them is important for working with web documents.
The Document type represents the entire web page. For example, the ownerDocument property of an element returns the document to which it belongs. The document is the root object in the DOM and provides methods to access and manipulate its content.
A Node refers to any object within a document. This can include elements, text, and attributes. Every item in a webpage, such as headings, paragraphs, or links, is considered a node.
An Element is a specific type of node representing an HTML element. For example, the document.createElement() method creates an element node. Elements also implement the HTMLElement interface, which provides additional functionality for handling different types of elements, such as tables or forms.
A NodeList is a collection of nodes, similar to an array. It is commonly returned by methods like document.querySelectorAll(). Nodes in a NodeList can be accessed using index notation, such as list, or by using the item() method.
The Attr type represents an attribute of an element. While attributes are considered nodes in the DOM, they are not typically manipulated as standalone objects. Instead, they are usually modified through element properties, such as element.setAttribute().
A NamedNodeMap is a collection of attributes or other named nodes that can be accessed by name or index. Unlike arrays, the order of items in a NamedNodeMap is not fixed. This type is used when working with attributes of an element, allowing them to be added or removed dynamically.
In the context of the DOM, certain terms are commonly used. For example, an Attr node is often simply called an “attribute,” and a collection of nodes is frequently referred to as a “NodeList.” Understanding these fundamental data types helps in effectively interacting with the DOM.
Understanding DOM Interfaces
Different objects interact within the DOM through various interfaces that provide access to elements and their properties. Since DOM objects can implement multiple interfaces, recognizing their relationships is essential for modifying and managing web page elements effectively.
For example, an HTML form element gets its name property from the HTMLFormElement interface but its className property from the HTMLElement interface. Both properties are accessible through the same form object, even though they come from different interfaces.
Interfaces and Objects
Many objects in the DOM implement multiple interfaces. A <table> element, for instance, uses:
- The HTMLTableElement interface, which provides methods like createCaption() and insertRow();
- The Element interface, which defines common element properties;
- The Node interface, which represents any node in the document tree.
When working with a table object, you may unknowingly use these interfaces interchangeably. In the following example, a table’s attributes are accessed through the Node and Element interfaces, while properties like border and summary come from the HTMLTableElement interface:
const table = document.getElementById(“table”);
const tableAttrs = table.attributes; // Accessing attributes via Node/Element interface
for (let i = 0; i < tableAttrs.length; i++) {
if (tableAttrs[i].nodeName.toLowerCase() === “border”) {
table.border = “1”; // Setting border using HTMLTableElement interface
}
}
table.summary = “note: increased border”; // Setting summary attribute via HTMLTableElement interface
Commonly Used Interfaces in the DOM
Several core interfaces are frequently used when interacting with the DOM. The document and window objects are among the most commonly accessed, where:
- The window object represents the browser environment;
- The document object functions as the root of the HTML document.
The Element interface, which extends from Node, provides various methods and properties for working with individual elements. Some elements also have specialized interfaces for specific data types, like HTMLTableElement for table manipulation.
Here are some commonly used DOM methods and properties:
- document.querySelector() – Selects the first matching element;
- document.querySelectorAll() – Selects all matching elements;
- document.createElement() – Creates a new element;
- Element.innerHTML – Gets or sets the HTML content of an element;
- Element.setAttribute() – Adds or modifies an attribute;
- Element.getAttribute() – Retrieves an attribute value;
- EventTarget.addEventListener() – Attaches an event listener to an element;
- HTMLElement.style – Modifies an element’s inline styles;
- Node.appendChild() – Adds a new child node to an element;
- window.onload – Executes a function when the page loads;
- window.scrollTo() – Scrolls the page to a specific position.
Understanding these interfaces and their functions helps in efficiently manipulating web pages using the DOM.
Example
Modifying Text Content
This example demonstrates how to dynamically update text inside a <textarea> using JavaScript. The interface consists of a <textarea> and two buttons—one to set text and another to clear it.
Key Concepts Used:
- document.querySelector() – Selects the <textarea> and buttons;
- addEventListener() – Listens for button clicks;
- textContent – Modifies the text inside the <textarea>.
HTML
<div class=”container”>
<textarea class=”story”></textarea>
<button id=”set-text” type=”button”>Set text content</button>
<button id=”clear-text” type=”button”>Clear text content</button>
</div>
CSS
.container {
display: flex;
gap: 0.5rem;
flex-direction: column;
}
button {
width: 200px;
}
JavaScript
const story = document.querySelector(“.story”);
const setText = document.querySelector(“#set-text”);
setText.addEventListener(“click”, () => {
story.textContent = “It was a dark and stormy night…”;
});
const clearText = document.querySelector(“#clear-text”);
clearText.addEventListener(“click”, () => {
story.textContent = “”;
});
When the first button is clicked, text appears in the <textarea>. Clicking the second button clears the text.
Result
Adding and Removing a Child Element
This example demonstrates how to dynamically create and remove a child element inside a <div>. Clicking the first button adds a new element, while clicking the second button removes it.
Key Concepts Used:
- document.querySelector() – Selects the parent <div> and buttons;
- addEventListener() – Listens for button clicks;
- createElement() – Creates a new element;
- appendChild() – Adds the child element;
- removeChild() – Removes the child element.
HTML
<div class=”container”>
<div class=”parent”>parent</div>
<button id=”add-child” type=”button”>Add a child</button>
<button id=”remove-child” type=”button”>Remove child</button>
</div>
CSS
.container {
display: flex;
gap: 0.5rem;
flex-direction: column;
}
button {
width: 100px;
}
div.parent {
border: 1px solid black;
padding: 5px;
width: 100px;
height: 100px;
}
div.child {
border: 1px solid red;
margin: 10px;
padding: 5px;
width: 80px;
height: 60px;
box-sizing: border-box;
}
JavaScript
const parent = document.querySelector(“.parent”);
const addChild = document.querySelector(“#add-child”);
addChild.addEventListener(“click”, () => {
// Add a child only if one doesn’t already exist
if (parent.childNodes.length > 1) {
return;
}
const child = document.createElement(“div”);
child.classList.add(“child”);
child.textContent = “child”;
parent.appendChild(child);
});
const removeChild = document.querySelector(“#remove-child”);
removeChild.addEventListener(“click”, () => {
const child = document.querySelector(“.child”);
if (child) {
parent.removeChild(child);
}
});
Clicking “Add a child” creates a new <div> inside the parent. Clicking “Remove child” deletes it.
Result
Conclusion
The Document Object Model (DOM) provides a structured way to access and modify web pages. It allows scripts to interact with elements, change content, and respond to user actions. By using JavaScript and the DOM API, developers can create dynamic and interactive web applications. Understanding the core concepts, such as nodes, elements, interfaces, and commonly used methods, is essential for working with web documents efficiently.
Posted in blog, Web Applications
Alex Carter
Alex Carter is a cybersecurity enthusiast and tech writer with a passion for online privacy, website performance, and digital security. With years of experience in web monitoring and threat prevention, Alex simplifies complex topics to help businesses and developers safeguard their online presence. When not exploring the latest in cybersecurity, Alex enjoys testing new tech tools and sharing insights on best practices for a secure web.