DOM API in One Go!
Why Learn the DOM API?
When a web page loads an HTML document, the browser generates the DOM, allowing developers to programmatically manipulate the entire page document through the DOM API. Since JavaScript does not understand the structure of HTML, the DOM generated by the browser represents HTML in an “object” format. In simple terms, learning the DOM API helps us use JavaScript to manipulate any element on the web page!
If we visualize the DOM as a chart, it would appear as a “tree structure,” representing the graphical depiction of the DOM architecture, as shown below:

What is a DOM Node?
Name | Description |
---|---|
Document Node | Represents the starting point of the entire document, the origin of all nodes |
Element Node | Represents elements (Element), such as <div> , <script> , <h1> |
Attribute Node | Represents attributes of elements like id , class |
Text Node | Represents plain text content within elements or attributes; line breaks and spaces are also a type of text node. |
Comment Node | Represents comments in the document |
Everything in an HTML document is a type of DOM node, and common nodes can be referenced in the chart above. Nodes are the fundamental building blocks of the DOM, and understanding the different types of nodes helps clarify what content you want to select, what you have selected, and how to handle it. Later in the article, you will learn various methods to select these different types of nodes, allowing you to programmatically manipulate and listen to them to achieve programmatic control over the web page.
Next, we will divide the content into three main sections, learning step by step how to use JavaScript to manipulate web pages through the DOM API, learning to access, edit, and listen to the DOM.
1. Selecting DOM Nodes
HTML elements have a hierarchical relationship, which is also reflected in the structure of the DOM. You can grab different related nodes based on a single node. For example, consider the following code:
<div> <h2>A List</h2> <ul> <li>List Item 01</li> <li>List Item 02</li> </ul></div>
For the <ul>
element: <h2>
is its sibling, <div>
is its parent, and <li>
is its child. Once you understand the relationships between elements, you can use different methods to select nodes in the web page.
Common Practical Examples
In most situations, you don’t need to remember too many selection methods; just remember the commonly used ones. For example, using querySelector
for selecting a single element and querySelectorAll
for selecting multiple elements can handle about 90% of scenarios.
<div id="foobar" class="foobar">Hello, World</div><ul> <li>Item 01</li> <li>Item 02</li> <li>Item 03</li></ul>
<script> // Select elements matching the .foobar selector group based on document const foobar = document.querySelector('.foobar'); // Select all li within ul based on document const foobar2 = document.querySelectorAll('ul li');</script>
More Advanced DOM Node Selection
After practicing different methods of selecting DOM elements, you’ll find that the results returned by different methods can vary. This is because they select different “things.” There are four types of results you may encounter. The details are summarized in the following list and table:
Node
The basic building block of the DOM; anything in the DOM is a node.
Element
An element is a type of node. For example, <h1>
, <body>
, and <div>
are all elements.
NodeList
A collection of nodes, similar to an array, with indexing and a forEach
method. Most of the time, it is static, meaning changes in the DOM do not reflect in the data.
HTMLCollection
A collection of elements, similar to an array, with indexing. It is a dynamic collection, meaning changes in the DOM will reflect in the data.
Name | Element | Node |
---|---|---|
Content | Only allows HTML elements (like <span> , <div> , etc.) | Allows any node present in the HTML document (comments, text nodes count) |
Methods and Properties | A special type of node with some extra properties | The most basic HTML component with some fundamental properties |
When to Use | Most of the time | When selecting things other than HTML tags |
Name | HTMLCollection | NodeList |
---|---|---|
Description | A collection of document elements | A collection of document nodes |
Array Methods Available | None | Only forEach |
Live Update | Yes | Mostly not |
2. Editing DOM Nodes
After selecting the DOM nodes, let’s print the results to see what properties are available:
<div id="foobar">Hello</div>
<script> // Based on the document, select the first element with id foobar and print it console.log(document.getElementById('foobar'));</script>
You will get a print result similar to the one shown in the animated image below:
You can see that each element object has many properties, which may seem very complex. However, the commonly used properties are actually not many, and you can refer to the documentation when needed. Below are examples of the two most commonly selected property types (changing styles and content):
Changing Element Style
To modify the style of an element, you can start with the class
property and the style
property. You can directly modify the element’s properties to achieve the style changes. For example:
// Modify the element's style property:element.style.backgroundColor = 'red';element.style.marginTop = '16px';element.style['padding-top'] = '16px';
// Modify the element's style property:element.classList.add('active'); // Add "active" classelement.classList.remove('active'); // Remove "active" classelement.classList.toggle('active'); // Toggle "active" class
Changing Element Content
To modify the content of an element, it can generally be divided into “modifying HTML” and “modifying plain text,” depending on the needs. For example:
// Modify the HTML content of the selected elementdocument.getElementById('foobar').innerHTML = '<h1>This is some text</h1>';// Modify the text content of the selected elementdocument.getElementById('foobar').innerText = 'This is some text';
3. Listening to DOM Nodes
addEventListener Event Listener
If you want to know what interactions users have with the webpage, you can use the addEventListener
method to listen for element activities. Most of the time, examples one and two can meet all event listening requirements. The syntax is as follows:
addEventListener(type, listener, options);
- Parameter one: Type of event
- Parameter two: Callback function, which will be executed when the event is triggered
- Parameter three: Specifies the options related to the event listener
// Use the element's addEventListener method to call the clicked function when "click" occurs// All three of the following methods are valid
// Example one: Call an external functionelement.addEventListener('click', clicked);function clicked() { // ...}
// Example two: Call an anonymous functionelement.addEventListener('click', function () { // ...});
// Example three: Add a settings object: this event listener will stop listening after being activated onceelement.addEventListener('click', function () {}, { once: true });
removeEventListener Remove Event Listener
When event listeners are no longer needed, they can be manually removed to avoid performance issues caused by too many background event listeners. This method can only remove event listeners that are executed by calling external functions; event listeners that call anonymous functions cannot be removed.
// Add listenerelement.addEventListener('mousemove', myFunction);
// Remove listenerelement.removeEventListener('mousemove', myFunction);
Listening to Forms
When you want users to input data, that’s where the <form>
comes into play. It provides a series of basic methods and interfaces that allow us to conveniently, quickly, and standardize the retrieval of user input data. The submit
event listener can be used to capture the submitted form.
<form data-form> <input name="userInput" type="text"> // Set name for later retrieval <input type="submit"></form>
const form = document.querySelector('[data-form]');// Handle submissionform.addEventListener('submit', (e) => { console.log(e.target.userInput.value); // Get the value of name = "userInput" e.preventDefault(); // Cancel default event (redirect page) e.target.reset(); // Clear the form});
Preventing Default Behavior
Certain elements have default “events,” such as clicking <a>
or submitting <form>
, which will redirect to other pages. In these cases, preventDefault
can be used to cancel these default events. Additionally, passing false
at the end of the event listener also has the same effect of preventing default behavior.
element.addEventListener('click', (e) => { e.preventDefault(); // Capture the event and prevent default behavior});
Summary
- The DOM is a way to represent documents as objects, structured like a tree.
- Any information in an HTML document is a type of node in the DOM.
- Selecting multiple nodes returns a NodeList, while selecting multiple elements returns an HTMLCollection; both are array-like objects.
- Nodes have many default methods and properties that can be queried after printing them in the terminal.
This article is based on the introductory topic I covered in the Hex School JS live class, which includes answers. If you’re interested, feel free to practice here: JS Live Class - Fall 2022 - DOM Manipulation