JavaScript DOM Introduction
What is the DOM?
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; this way, programming languages like JavaScript can interact with the page.
Think of the DOM as a tree-like structure where each node represents a part of the document. This structure allows developers to:
- Access and manipulate HTML elements
- Change element attributes
- Add or remove elements
- React to user events (clicks, form submissions, etc.)
Why is the DOM important?
Before the DOM, web pages were static. Once a page loaded, its content remained unchanged unless you navigated to a new page. With the DOM and JavaScript, we can:
- Create dynamic, interactive web applications
- Update content without refreshing the page
- Respond to user actions in real-time
- Validate form inputs before submission
- Create animations and visual effects
The DOM Tree Structure
When a browser loads an HTML document, it creates a model of that document called the DOM tree. Let's look at a simple HTML document:
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
</head>
<body>
<h1 id="main-heading">Welcome to My Page</h1>
<p>This is a <span class="highlight">simple</span> paragraph.</p>
</body>
</html>
The corresponding DOM tree looks like this:
document
└── html
├── head
│ └── title
│ └── "My Web Page"
└── body
├── h1 (id="main-heading")
│ └── "Welcome to My Page"
└── p
├── "This is a "
├── span (class="highlight")
│ └── "simple"
└── " paragraph."
Accessing DOM Elements
JavaScript provides several methods to access elements within the DOM:
1. getElementById
Selects an element by its unique ID.
// HTML: <h1 id="main-heading">Welcome to My Page</h1>
const headingElement = document.getElementById("main-heading");
console.log(headingElement.textContent); // Output: "Welcome to My Page"
2. getElementsByClassName
Returns a collection of elements with a specific class name.
// HTML: <span class="highlight">simple</span>
const highlightElements = document.getElementsByClassName("highlight");
console.log(highlightElements.length); // Output: 1
console.log(highlightElements[0].textContent); // Output: "simple"
3. getElementsByTagName
Returns a collection of elements with a specific tag name.
// HTML: <p>This is a <span class="highlight">simple</span> paragraph.</p>
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length); // Output: 1
console.log(paragraphs[0].textContent); // Output: "This is a simple paragraph."
4. querySelector
Returns the first element that matches a CSS selector.
// HTML: <span class="highlight">simple</span>
const highlightElement = document.querySelector(".highlight");
console.log(highlightElement.textContent); // Output: "simple"
5. querySelectorAll
Returns all elements that match a CSS selector.
// HTML: <span class="highlight">simple</span>
const elements = document.querySelectorAll(".highlight");
console.log(elements.length); // Output: 1
Modifying DOM Elements
Once you've accessed an element, you can modify its content and attributes:
Changing Text Content
const heading = document.getElementById("main-heading");
heading.textContent = "Updated Heading";
console.log(heading.textContent); // Output: "Updated Heading"
Modifying HTML Content
const paragraph = document.getElementsByTagName("p")[0];
paragraph.innerHTML = "This is an <strong>updated</strong> paragraph.";
// The paragraph now contains bold text for the word "updated"
Changing Attributes
const heading = document.getElementById("main-heading");
heading.setAttribute("class", "title-text");
console.log(heading.getAttribute("class")); // Output: "title-text"
// You can also access attributes directly (for most standard attributes)
heading.className = "main-title";
console.log(heading.className); // Output: "main-title"
Modifying Styles
const heading = document.getElementById("main-heading");
heading.style.color = "blue";
heading.style.backgroundColor = "yellow";
heading.style.fontSize = "24px";
Creating and Removing Elements
Creating New Elements
// Create a new paragraph element
const newParagraph = document.createElement("p");
newParagraph.textContent = "This is a dynamically created paragraph.";
// Add it to the body
document.body.appendChild(newParagraph);
Removing Elements
// Remove the paragraph we just created
document.body.removeChild(newParagraph);
// Another way: get the element and tell its parent to remove it
const heading = document.getElementById("main-heading");
heading.parentNode.removeChild(heading);
Real-World Example: Dynamic Content Updater
Let's create a simple application that updates content based on user interaction:
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Content Example</title>
<style>
.box {
border: 1px solid #ccc;
padding: 20px;
margin: 20px;
background-color: #f9f9f9;
}
</style>
</head>
<body>
<div class="box" id="content-box">
<h2>Welcome to our website!</h2>
<p>Click a button below to update this content:</p>
</div>
<button id="btn-about">About Us</button>
<button id="btn-services">Our Services</button>
<button id="btn-contact">Contact Info</button>
<script>
// Get the content box and buttons
const contentBox = document.getElementById("content-box");
const aboutBtn = document.getElementById("btn-about");
const servicesBtn = document.getElementById("btn-services");
const contactBtn = document.getElementById("btn-contact");
// Add event listeners to buttons
aboutBtn.addEventListener("click", function() {
contentBox.innerHTML = `
`;
contentBox.style.backgroundColor = "#e6f7ff";
});
servicesBtn.addEventListener("click", function() {
contentBox.innerHTML = `
`;
contentBox.style.backgroundColor = "#e6ffe6";
});
contactBtn.addEventListener("click", function() {
contentBox.innerHTML = `
`;
contentBox.style.backgroundColor = "#ffe6e6";
});
</script>
</body>
</html>
In this example:
- We have a content box and three buttons
- Each button updates the content and background color of the box
- We use
innerHTML
to replace the entire contents - We modify the style directly with JavaScript
Summary
In this introduction to the JavaScript DOM, we've learned:
- What the DOM is: A structured representation of HTML documents
- DOM tree structure: How browsers organize document elements
- Accessing elements: Different methods to select elements
- Modifying elements: Changing content, attributes, and styles
- Creating and removing elements: Dynamically updating the page
- A practical application: Building a simple content updater
The DOM is fundamental to web development, forming the bridge between HTML content and JavaScript functionality. By understanding how to manipulate the DOM, you're taking the first step toward building interactive web applications.
Exercises to Practice
- Create a simple to-do list application where users can add and remove items
- Build a form that validates user input without submitting to a server
- Create a color changer that updates the background color when different buttons are clicked
- Build an image slider that changes images when next/previous buttons are clicked
- Create a simple calculator interface that displays the results of operations
Additional Resources
- MDN Web Docs: Document Object Model
- W3Schools DOM Tutorial
- JavaScript.info DOM Nodes
- DOM Enlightenment - A free online book about the DOM
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)