Skip to main content

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:

  1. Create dynamic, interactive web applications
  2. Update content without refreshing the page
  3. Respond to user actions in real-time
  4. Validate form inputs before submission
  5. 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:

html
<!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.

javascript
// 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.

javascript
// 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.

javascript
// 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.

javascript
// 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.

javascript
// 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

javascript
const heading = document.getElementById("main-heading");
heading.textContent = "Updated Heading";
console.log(heading.textContent); // Output: "Updated Heading"

Modifying HTML Content

javascript
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

javascript
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

javascript
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

javascript
// 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

javascript
// 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:

html
<!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 = `
<h2>About Us</h2>
<p>We are a company focused on creating amazing web experiences.</p>
<p>Founded in 2010, we've helped hundreds of clients achieve their goals.</p>
`;
contentBox.style.backgroundColor = "#e6f7ff";
});

servicesBtn.addEventListener("click", function() {
contentBox.innerHTML = `
<h2>Our Services</h2>
<ul>
<li>Web Development</li>
<li>Mobile Applications</li>
<li>UI/UX Design</li>
</ul>
`;
contentBox.style.backgroundColor = "#e6ffe6";
});

contactBtn.addEventListener("click", function() {
contentBox.innerHTML = `
<h2>Contact Information</h2>
<p>Email: [email protected]</p>
<p>Phone: (123) 456-7890</p>
<p>Address: 123 Web Dev Lane, Internet City</p>
`;
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:

  1. What the DOM is: A structured representation of HTML documents
  2. DOM tree structure: How browsers organize document elements
  3. Accessing elements: Different methods to select elements
  4. Modifying elements: Changing content, attributes, and styles
  5. Creating and removing elements: Dynamically updating the page
  6. 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

  1. Create a simple to-do list application where users can add and remove items
  2. Build a form that validates user input without submitting to a server
  3. Create a color changer that updates the background color when different buttons are clicked
  4. Build an image slider that changes images when next/previous buttons are clicked
  5. Create a simple calculator interface that displays the results of operations

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)