The Document Object Model (DOM) is a programming interface that represents an HTML or XML document as a tree of objects. JavaScript can use the DOM to read and change page content, structure, styles, and attributes, as well as respond to user actions such as clicks and keyboard input. The DOM is what allows a web page to become interactive instead of remaining a static document.
1. What Is the Document Object Model (DOM)?
When a browser loads an HTML page, it parses the markup and creates an in-memory representation of the document. This representation is called the Document Object Model. Each HTML element becomes a node in a hierarchical tree, and JavaScript can access these nodes through the browser’s DOM APIs.
Consider this simple HTML document:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Welcome</h1>
<p>Learn JavaScript DOM.</p>
</body>
</html>
The browser creates objects for the document, the HTML element, the head, the body, the heading, and the paragraph. These objects are connected in a parent-child relationship.
2. Understanding the DOM Tree
The DOM represents a document as a tree. The top-level document object contains the root html element. The html element contains the head and body elements, and those elements contain their own child nodes.
Document
└── html
├── head
│ └── title
│ └── "My Website"
└── body
├── h1
│ └── "Welcome"
└── p
└── "Learn JavaScript DOM."
In this tree, html is the parent of head and body. The heading and paragraph are children of body. Text inside an element is represented by text nodes.
3. Types of DOM Nodes
The DOM includes different node types. The most common ones you will work with are:
- Document node: Represents the entire document and is available through the global
documentobject. - Element node: Represents an HTML element such as
div,p, orbutton. - Text node: Represents text inside an element.
- Comment node: Represents an HTML comment.
- Attribute: Attributes are exposed through element attribute APIs and are not child nodes in the ordinary element tree.
4. The document Object
The document object is the main entry point for working with the current web page. It provides methods and properties for finding elements, creating nodes, and accessing document information.
console.log(document.title);
console.log(document.URL);
console.log(document.body);
console.log(document.documentElement);
document.title reads the page title, document.URL returns the document URL, document.body refers to the body element, and document.documentElement refers to the root html element.
5. Selecting HTML Elements
Before changing an element, you usually need to select it. JavaScript provides several DOM methods for finding elements.
A. getElementById()
Use getElementById() to select the element with a specific ID. It returns the matching element or null if no element is found.
<h1 id="heading">Hello World</h1>
<script>
const heading = document.getElementById("heading");
console.log(heading.textContent);
</script>
B. getElementsByClassName()
This method returns a live HTMLCollection containing elements with the specified class name.
const items = document.getElementsByClassName("item");
console.log(items.length);
for (const item of items) {
console.log(item.textContent);
}
C. getElementsByTagName()
Use this method to select elements by their tag name. It also returns a live HTMLCollection.
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length);
D. querySelector()
querySelector() accepts a CSS selector and returns the first matching element. It supports selectors such as IDs, classes, attributes, and combinations of selectors.
const firstItem = document.querySelector(".item");
const heading = document.querySelector("#heading");
const button = document.querySelector("button.primary");
E. querySelectorAll()
querySelectorAll() returns a static NodeList containing all elements that match a CSS selector. You can use forEach() to process its elements.
const allItems = document.querySelectorAll(".item");
allItems.forEach(function(item) {
console.log(item.textContent);
});
6. Changing HTML Content
After selecting an element, you can update its text or HTML content. Use textContent when inserting plain text. Use innerHTML only when you intentionally need to parse HTML and the content is trusted or safely sanitized.
<h2 id="message">Old Message</h2>
<script>
const message = document.getElementById("message");
message.textContent = "Welcome to JavaScript DOM!";
</script>
You can also read or replace an element’s HTML markup with innerHTML. Avoid assigning untrusted user input to innerHTML, because it can create cross-site scripting (XSS) vulnerabilities. For plain user-provided text, use textContent.
7. Changing CSS Styles
JavaScript can modify an element’s inline styles through its style property. CSS property names that contain hyphens are written in camelCase in JavaScript.
const title = document.querySelector("h1");
title.style.color = "blue";
title.style.backgroundColor = "lightyellow";
title.style.fontSize = "32px";
For reusable styling, it is usually cleaner to define a CSS class and add or remove that class with classList.
const box = document.querySelector(".box");
box.classList.add("active");
box.classList.remove("hidden");
box.classList.toggle("highlight");
8. Working with HTML Attributes
DOM elements provide methods such as getAttribute(), setAttribute(), hasAttribute(), and removeAttribute() to work with HTML attributes.
<img id="photo" src="old-image.jpg" alt="Old photo"> <script> const image = document.getElementById("photo"); console.log(image.getAttribute("src")); image.setAttribute("src", "new-image.jpg"); image.setAttribute("alt", "A new photo"); console.log(image.hasAttribute("alt")); image.removeAttribute("title"); </script>
