Mapagam
  • JavaScript 
  • Web APIs 
  • TypeScript 
  • React 

How to Manipulate HTML Elements Using the DOM API

Posted on March 30, 2025 • 6 min read • 1,199 words
Share via
Mapagam
Link copied to clipboard

Learn how to manipulate HTML elements using the DOM API, with tips on accessing, modifying, and interacting with elements dynamically.

On this page
1. Introduction to the DOM API 1.1 What is the DOM? 1.2 Why is the DOM Important for Web Development? 2. Basic DOM Manipulation Methods 2.1 Accessing DOM Elements 2.2 Modifying Element Content 2.3 Modifying Element Attributes 2.4 Adding and Removing Elements 3. Event Handling and DOM Interaction 3.1 Adding Event Listeners 3.2 Removing Event Listeners 4. Advanced DOM Manipulation Techniques 4.1 Modifying CSS Styles Dynamically 4.2 DOM Traversal 5. Best Practices for DOM Manipulation 5.1 Batch DOM Changes 5.2 Avoid Manipulating the DOM During Loops 5.3 Use Delegated Events 6. Conclusion

The Document Object Model (DOM) is an essential tool for web developers, enabling interaction with and manipulation of HTML elements. The DOM represents a page as a tree structure, where each node corresponds to a part of the page’s structure (such as an element or an attribute). With the DOM API, developers can dynamically alter a webpage’s content, structure, and style, enhancing user experience.

1. Introduction to the DOM API

The DOM (Document Object Model) is an interface that allows scripts to dynamically access and update the content, structure, and styles of a web document. When a webpage is loaded in the browser, the browser creates a DOM of the page, making it accessible via JavaScript. This structure allows developers to modify the webpage in real-time.

1.1 What is the DOM?

The DOM is essentially a representation of an HTML or XML document as a tree structure. Each part of the document (elements, attributes, and text) is represented as a node in the tree. The DOM API allows developers to interact with this tree using JavaScript, enabling them to change the page’s content, add new elements, or even delete existing ones.

1.2 Why is the DOM Important for Web Development?

The DOM is integral to client-side scripting, as it gives developers the ability to manipulate HTML content directly. This means that pages can be updated without reloading, improving user experience and providing a more interactive web environment.

2. Basic DOM Manipulation Methods

To start manipulating HTML elements using the DOM API, we first need to understand some basic methods that help us interact with elements.

2.1 Accessing DOM Elements

Before we can modify any HTML element, we need to access it. This can be done in several ways, each suited for different use cases.

2.1.1 Using getElementById()

This method allows you to access a single HTML element by its unique id attribute.

const element = document.getElementById("myElement");

2.1.2 Using getElementsByClassName()

If you need to select multiple elements with the same class name, you can use this method. It returns a live HTMLCollection of elements with the specified class name.

const elements = document.getElementsByClassName("myClass");

2.1.3 Using getElementsByTagName()

This method retrieves all elements with a given tag name (such as <p> or <div>).

const divs = document.getElementsByTagName("div");

2.1.4 Using querySelector() and querySelectorAll()

The querySelector() method returns the first element that matches a given CSS selector, while querySelectorAll() returns a static NodeList of all matching elements.

const firstDiv = document.querySelector("div");
const allDivs = document.querySelectorAll("div");

These methods offer flexibility by enabling you to use CSS selectors to target elements more specifically.

2.2 Modifying Element Content

Once an element is selected, the next step is modifying its content. There are several properties and methods for this.

2.2.1 innerHTML

The innerHTML property allows you to get or set the HTML content inside an element.

element.innerHTML = "<p>This is new content!</p>";

2.2.2 textContent

Unlike innerHTML, which parses HTML tags inside the content, textContent only works with the text inside the element. It is ideal for text manipulation without modifying the underlying HTML structure.

element.textContent = "This is some plain text!";

2.3 Modifying Element Attributes

Attributes like src for images or href for links can also be altered using the DOM API.

2.3.1 setAttribute()

This method allows you to change the value of an attribute.

element.setAttribute("src", "newImage.jpg");

2.3.2 getAttribute()

You can retrieve the value of an attribute using this method.

const srcValue = element.getAttribute("src");

2.3.3 removeAttribute()

This method removes a specified attribute from an element.

element.removeAttribute("disabled");

2.4 Adding and Removing Elements

Sometimes, you might need to add new elements or remove existing ones from the DOM.

2.4.1 createElement()

The createElement() method is used to create a new HTML element.

const newDiv = document.createElement("div");

2.4.2 appendChild()

This method appends a new child element to a parent element.

const parent = document.getElementById("parentElement");
parent.appendChild(newDiv);

2.4.3 removeChild()

To remove a child element from the DOM, use removeChild().

parent.removeChild(newDiv);

3. Event Handling and DOM Interaction

In addition to modifying elements, the DOM API also allows developers to interact with elements based on user actions, such as clicks, keystrokes, or mouse movements. Event handling is a critical part of web development and enables dynamic behavior on the page.

3.1 Adding Event Listeners

To respond to user interactions, you can add event listeners to DOM elements. This allows specific code to run when certain events occur.

3.1.1 Using addEventListener()

The addEventListener() method attaches an event handler to an element. For example, you can add a click event listener to a button:

const button = document.getElementById("myButton");
button.addEventListener("click", function() {
    alert("Button clicked!");
});

3.2 Removing Event Listeners

If you no longer need an event listener, you can remove it using removeEventListener().

button.removeEventListener("click", myFunction);

4. Advanced DOM Manipulation Techniques

While basic DOM manipulation covers most use cases, there are more advanced methods that can be utilized to create rich, interactive web experiences.

4.1 Modifying CSS Styles Dynamically

One of the powerful aspects of the DOM API is the ability to modify CSS styles programmatically. This allows you to create responsive designs or visual effects without having to reload the page.

4.1.1 Accessing Inline Styles

You can directly modify an element’s inline styles using the style property.

element.style.color = "red";
element.style.fontSize = "20px";

4.1.2 Modifying Class List

The classList property provides methods to add, remove, and toggle CSS classes on an element.

element.classList.add("active");
element.classList.remove("inactive");
element.classList.toggle("highlight");

4.2 DOM Traversal

Sometimes, you need to navigate through elements in the DOM tree. Traversal methods allow you to access parent, sibling, and child elements relative to a selected node.

4.2.1 Navigating Parent and Child Nodes

You can access a node’s parent or child elements using the parentNode, childNodes, firstChild, and lastChild properties.

const parent = element.parentNode;
const firstChild = element.firstChild;

4.2.2 Navigating Sibling Nodes

To move between sibling elements, use previousElementSibling and nextElementSibling.

const previousSibling = element.previousElementSibling;
const nextSibling = element.nextElementSibling;

5. Best Practices for DOM Manipulation

Manipulating the DOM can be an expensive operation in terms of performance, especially when done excessively. Here are some best practices to ensure efficient DOM manipulation:

5.1 Batch DOM Changes

Instead of making multiple changes to the DOM one by one, it’s better to make all changes in a single batch. This minimizes reflows and repaints in the browser, which can improve performance.

const fragment = document.createDocumentFragment();
// Add all elements to the fragment
fragment.appendChild(newElement);
parent.appendChild(fragment);

5.2 Avoid Manipulating the DOM During Loops

If you’re looping through elements to manipulate the DOM, do so in memory first and update the DOM after the loop. This avoids repeated reflows.

5.3 Use Delegated Events

Event delegation is a technique where a single event listener is added to a parent element, and events are handled based on the event target. This can significantly reduce the number of event listeners in a large app.

parentElement.addEventListener("click", function(event) {
    if (event.target && event.target.matches("button")) {
        // Handle button click
    }
});

6. Conclusion

The DOM API is a powerful tool for web developers, offering the ability to manipulate HTML elements dynamically and interactively. By understanding the methods for accessing, modifying, and manipulating DOM elements, you can create more engaging and responsive web applications. The ability to handle events, update content, and modify styles on the fly ensures that users have a seamless browsing experience.

DOM API   HTML Manipulation   JavaScript DOM   Web Development   Dynamic Content  
DOM API   HTML Manipulation   JavaScript DOM   Web Development   Dynamic Content  
 What Is the Console API? Debugging JavaScript Easily
JavaScript DOM API Explained Simply 

More Reading!

  1. How to Use the Geolocation API in JavaScript (With Live Demo)
  2. Understanding the JavaScript Clipboard API for Seamless Copy-Paste
  3. Beginner’s Guide to the JavaScript DOM API (With Practical Examples)
  4. Using the History API for Simple Navigation in JavaScript
  5. How to Access User Media with the MediaDevices API
On this page:
1. Introduction to the DOM API 1.1 What is the DOM? 1.2 Why is the DOM Important for Web Development? 2. Basic DOM Manipulation Methods 2.1 Accessing DOM Elements 2.2 Modifying Element Content 2.3 Modifying Element Attributes 2.4 Adding and Removing Elements 3. Event Handling and DOM Interaction 3.1 Adding Event Listeners 3.2 Removing Event Listeners 4. Advanced DOM Manipulation Techniques 4.1 Modifying CSS Styles Dynamically 4.2 DOM Traversal 5. Best Practices for DOM Manipulation 5.1 Batch DOM Changes 5.2 Avoid Manipulating the DOM During Loops 5.3 Use Delegated Events 6. Conclusion
Follow me

I work on everything coding and technology

   
Mapagam
Mapagam is your go-to resource for all things related to frontend development. From the latest frameworks and libraries to tips, tutorials, and best practices, we dive deep into the ever-evolving world of web technologies.
Licensed under Creative Commons (CC BY-NC-SA 4.0).
 
Frontend
JavaScript 
Web Api 
TypeScript 
React 
Social
Linkedin 
Github 
Mapagam
Code copied to clipboard