
Document Object Model examples are one of the best ways for beginners to understand how JavaScript interacts with webpages. The Document Object Model, commonly called the DOM, allows JavaScript to access HTML elements, change content, modify styles, respond to user actions, and create or remove elements dynamically.
Instead of learning DOM concepts only through theory, working with practical examples makes it easier to understand how web pages become interactive. Whether you are creating a navigation menu, validating a form, building a to-do list, or updating content without refreshing the page, DOM manipulation is involved.
In this guide, we will explore practical Document Object Model examples using JavaScript. You will learn how to select elements, change text, modify CSS, handle events, work with attributes, create elements, remove elements, and build simple interactive features.
Table of Contents
What Is the Document Object Model?
The Document Object Model is a programming interface that represents an HTML document as a tree of objects.
For example, consider this HTML:
<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<p>Welcome to my website.</p>
</body>
</html>
The browser converts this HTML into a DOM tree. JavaScript can then access the elements represented in that tree.
The document object is the main entry point for interacting with the DOM.
For example:
console.log(document);
This allows JavaScript to access the current webpage and its elements.
Document Object Model Examples in JavaScript
The following examples demonstrate common ways developers use the DOM in real-world websites.
1. Selecting an Element by ID
One of the simplest Document Object Model examples is selecting an HTML element using its ID.
HTML:
<h1 id="title">Hello World</h1>
JavaScript:
const heading = document.getElementById("title");
console.log(heading);
The getElementById() method searches for an element with the specified ID.
Once the element has been selected, you can modify it.
For example:
heading.textContent = "Welcome to JavaScript!";
The heading displayed on the webpage will change immediately.
2. Selecting Elements with querySelector()
The querySelector() method allows you to select an element using a CSS selector.
For example:
<p class="description">Learn JavaScript</p>
You can select it using:
const paragraph = document.querySelector(".description");
You can also use an ID selector:
const title = document.querySelector("#title");
This method is useful because it supports familiar CSS selector syntax.
3. Selecting Multiple Elements
Sometimes you need to select multiple elements.
For example:
<ul>
<li class="item">HTML</li>
<li class="item">CSS</li>
<li class="item">JavaScript</li>
</ul>
JavaScript:
const items = document.querySelectorAll(".item");
console.log(items);
The querySelectorAll() method returns a collection containing all matching elements.
You can then loop through them:
items.forEach(function(item) {
console.log(item.textContent);
});
This technique is useful when working with lists, cards, menus, or groups of buttons.
4. Changing Text Content
Changing text dynamically is another basic JavaScript DOM example.
HTML:
<p id="message">Original message</p>
JavaScript:
const message = document.getElementById("message");
message.textContent = "The message has been updated!";
The browser immediately displays the new text.
textContent is useful when you want to insert plain text without interpreting it as HTML.
5. Changing HTML Content
JavaScript can also change the HTML inside an element using innerHTML.
For example:
const box = document.querySelector("#box");
box.innerHTML = "<strong>Hello JavaScript!</strong>";
The browser interprets the inserted markup as HTML.
Although innerHTML is convenient, developers should be careful when inserting content that comes from users or other untrusted sources. Improper use can create security vulnerabilities.
When you only need to change text, textContent is generally a safer and simpler option.
6. Changing CSS Styles
The DOM allows JavaScript to modify an element’s appearance.
HTML:
<p id="text">Change my style</p>
JavaScript:
const text = document.getElementById("text");
text.style.color = "blue";
text.style.fontSize = "24px";
The paragraph’s appearance changes immediately.
However, directly changing many style properties through JavaScript can become difficult to maintain. A better approach for larger projects is often to add or remove CSS classes.
7. Adding and Removing CSS Classes
The classList property makes it easy to manipulate CSS classes.
For example:
const box = document.querySelector(".box");
box.classList.add("active");
You can remove the class:
box.classList.remove("active");
Or toggle it:
box.classList.toggle("active");
This is particularly useful for interactive menus, dark-mode buttons, dropdowns, animations, and responsive interfaces.
8. Handling Button Clicks
Websites need to respond to user interactions.
The addEventListener() method allows JavaScript to listen for events.
HTML:
<button id="btn">Click Me</button>
JavaScript:
const button = document.getElementById("btn");
button.addEventListener("click", function() {
alert("Button clicked!");
});
When the user clicks the button, the function runs.
Event listeners are a fundamental part of DOM manipulation because they connect user actions to JavaScript functionality.
9. Building a Simple Counter
You can combine element selection, event handling, and text updates to create a simple counter.
HTML:
<p id="count">0</p>
<button id="increase">Increase</button>
JavaScript:
let count = 0;
const countDisplay = document.getElementById("count");
const increaseButton = document.getElementById("increase");
increaseButton.addEventListener("click", function() {
count++;
countDisplay.textContent = count;
});
Every time the button is clicked, the number increases.
This small project demonstrates how JavaScript can interact with the DOM to create dynamic interfaces.
10. Changing an Image
JavaScript can modify image attributes through the DOM.
HTML:
<img id="photo" src="image1.jpg" alt="Example image">
JavaScript:
const image = document.getElementById("photo");
image.src = "image2.jpg";
The image changes without reloading the page.
You can also modify the alt attribute:
image.alt = "New image description";
This technique can be used to create image galleries and simple image sliders.
11. Working with HTML Attributes
The setAttribute() method allows you to modify attributes.
For example:
const link = document.querySelector("a");
link.setAttribute("href", "https://example.com");
You can retrieve an attribute with:
const url = link.getAttribute("href");
You can also remove one:
link.removeAttribute("target");
Attribute manipulation is useful when dynamically changing links, images, form properties, and other HTML elements.
12. Creating a New Element
The DOM allows JavaScript to create completely new HTML elements.
For example:
const paragraph = document.createElement("p");
paragraph.textContent = "This paragraph was created using JavaScript.";
document.body.appendChild(paragraph);
The createElement() method creates the element, while appendChild() adds it to the webpage.
This technique is commonly used in applications that need to display dynamic content.
13. Removing an Element
JavaScript can also remove existing elements.
For example:
const message = document.querySelector("#message");
message.remove();
The selected element disappears from the document.
This can be useful for dismissible notifications, removing products from shopping carts, deleting to-do items, or closing modal windows.
14. Creating a Simple To-Do List
A to-do list is one of the best beginner projects for practicing DOM manipulation.
HTML:
<input id="taskInput" type="text">
<button id="addTask">Add Task</button>
<ul id="taskList"></ul>
JavaScript:
const input = document.getElementById("taskInput");
const button = document.getElementById("addTask");
const list = document.getElementById("taskList");
button.addEventListener("click", function() {
const task = input.value.trim();
if (task === "") {
return;
}
const item = document.createElement("li");
item.textContent = task;
list.appendChild(item);
input.value = "";
});
When the user enters a task and clicks the button, JavaScript creates a new list item and adds it to the DOM.
This simple project demonstrates several concepts together: selecting elements, handling events, reading input, creating elements, and modifying the page.
15. Handling Form Submission
The DOM is also useful for working with forms.
HTML:
<form id="myForm">
<input id="name" type="text">
<button type="submit">Submit</button>
</form>
JavaScript:
const form = document.getElementById("myForm");
form.addEventListener("submit", function(event) {
event.preventDefault();
console.log("Form submitted!");
});
preventDefault() stops the browser from performing its default form-submission behavior.
You can then validate the input or send the information to a server using JavaScript.
16. Using DOM Traversal
DOM traversal means moving between related elements.
For example:
const item = document.querySelector(".item");
console.log(item.parentElement);
console.log(item.children);
console.log(item.nextElementSibling);
These properties allow you to move from one element to its parent, children, or neighboring elements.
DOM traversal becomes especially useful when working with complex HTML structures.
17. Showing and Hiding Elements
Another common use of the DOM is showing or hiding content.
For example:
const menu = document.querySelector(".menu");
menu.classList.toggle("hidden");
A CSS class can control whether the element is visible.
This approach can be used for dropdown menus, mobile navigation, pop-ups, FAQs, and other interactive components.
Best Practices for DOM Manipulation
Learning JavaScript DOM manipulation is not only about knowing methods. You should also understand how to use them efficiently.
Select Elements Efficiently
Store frequently used elements in variables instead of repeatedly searching for the same elements.
Prefer Classes for Styling
Use CSS classes when possible rather than applying many inline styles through JavaScript.
Avoid Unnecessary DOM Updates
Repeatedly changing the DOM can affect performance, especially when working with large interfaces.
Use Event Listeners
addEventListener() provides a flexible way to respond to user interactions.
Keep JavaScript Organized
Separate your HTML, CSS, and JavaScript responsibilities where practical. This makes projects easier to maintain.
Why Practice DOM Examples?
Reading about the DOM is useful, but actually building small projects is much more effective.
Start with simple tasks such as changing text and responding to button clicks. Then progress to counters, image sliders, dropdown menus, forms, and to-do lists.
Each project introduces new concepts and helps you understand how JavaScript interacts with the browser.
Once you are comfortable with the basics, you can move on to frontend libraries and frameworks such as React, Vue, or Angular. Even when using these technologies, understanding the underlying DOM remains valuable.
Final Thoughts
These Document Object Model examples demonstrate how JavaScript can turn static HTML into interactive web experiences. You can select elements, change content, modify attributes and styles, respond to events, create new elements, and remove existing content.
The best way to learn the DOM is through practice. Start with individual techniques such as querySelector(), textContent, classList, and addEventListener(). Then combine them into small projects such as counters and to-do lists.
Once you understand these fundamentals, more advanced JavaScript and frontend development concepts become much easier to learn.
Frequently Asked Questions
1. What is the DOM in JavaScript?
The DOM is a programming interface that represents an HTML document as a tree of objects. JavaScript can use the DOM to access, modify, create, and remove elements on a webpage.
2. What are some common DOM examples?
Common examples include changing text, modifying CSS classes, handling button clicks, changing images, creating elements, removing elements, validating forms, and building interactive menus.
3. What is DOM manipulation?
DOM manipulation is the process of using JavaScript to modify a webpage’s structure, content, attributes, or styling. It is used to create dynamic and interactive web experiences.
4. How can beginners practice the DOM?
Beginners can practice by building small projects such as counters, to-do lists, image sliders, calculators, dropdown menus, and interactive forms. These projects provide practical experience with common DOM methods.


