The Document Object Model (DOM) is the bridge between HTML and JavaScript. It's a programming interface that represents your web page as a tree structure of objects, allowing JavaScript to access and manipulate HTML elements, styles, and content dynamically. Understanding the DOM is essential for creating interactive web pages—from updating text to building complex single-page applications. Let's explore this fundamental web technology!
What Is the DOM?
The DOM (Document Object Model) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content.
Think of the DOM as:
- A live representation of your HTML in memory
- A tree structure where everything is a node
- An API (interface) that JavaScript uses to interact with HTML
- A bridge connecting HTML, CSS, and JavaScript
Why the DOM Matters
<!-- Static HTML (without JavaScript) -->
<div id="greeting">Hello!</div>
<button>Click Me</button>
<!-- This page just sits there, unchanging -->
<!-- User clicks button → Nothing happens --><!-- Dynamic HTML (with JavaScript + DOM) -->
<div id="greeting">Hello!</div>
<button onclick="changeGreeting()">Click Me</button>
<script>
function changeGreeting() {
// JavaScript uses the DOM to find and change the element
let greeting = document.getElementById('greeting');
greeting.textContent = 'Hello, World!';
greeting.style.color = 'blue';
}
</script>
<!-- User clicks button → Text changes and turns blue! -->Key Concept: The DOM is created by the browser when it loads an HTML page. JavaScript can then use the DOM to make the page interactive and dynamic.
The DOM Tree Structure
The DOM represents your HTML document as a tree of nodes. Each HTML element becomes a node in this tree.
Simple HTML Example
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Welcome</h1>
<p>This is a paragraph.</p>
<div>
<button>Click Me</button>
</div>
</body>
</html>Visualized as a Tree
Document
└── html (root element)
├── head
│ └── title
│ └── "My Page" (text node)
└── body
├── h1
│ └── "Welcome" (text node)
├── p
│ └── "This is a paragraph." (text node)
└── div
└── button
└── "Click Me" (text node)Tree Terminology:
- Root: The top element (usually
<html>) - Parent: Element that contains other elements
- Child: Element inside another element
- Siblings: Elements at the same level
- Descendants: All elements nested inside (children, grandchildren, etc.)
- Ancestors: All parent elements above (parent, grandparent, etc.)
Types of Nodes
Everything in the DOM is a node, but there are different types of nodes.
<div id="container" class="box">
Hello World
<span>Text in span</span>
<!-- This is a comment -->
</div>Node Types in above HTML:
1. Element Node: <div>, <span>
2. Text Node: "Hello World", "Text in span"
3. Attribute Node: id="container", class="box"
4. Comment Node: <!-- This is a comment -->Node Types Explained
- Element Nodes: HTML tags like
<div>,<p>,<button> - Text Nodes: Actual text content inside elements
- Attribute Nodes: Attributes like
id,class,src - Comment Nodes: HTML comments
<!-- --> - Document Node: The entire document (root of tree)
// Accessing different node types
let container = document.getElementById('container');
console.log(container.nodeType); // 1 (Element node)
console.log(container.nodeName); // "DIV"
// First child is text node "Hello World"
let firstChild = container.firstChild;
console.log(firstChild.nodeType); // 3 (Text node)
console.log(firstChild.nodeValue); // "Hello World"
// Common node types (numbers)
// 1 = Element
// 3 = Text
// 8 = Comment
// 9 = DocumentThe Document Object
The document object is your entry point to the DOM. It represents the entire HTML page and provides methods to access elements.
Common Document Properties
// Access document properties
console.log(document.title); // Page title
console.log(document.URL); // Full URL
console.log(document.domain); // Domain name
// Access main elements
console.log(document.documentElement); // <html> element
console.log(document.head); // <head> element
console.log(document.body); // <body> element
// Get all elements of a type
console.log(document.links); // All <a> elements
console.log(document.images); // All <img> elements
console.log(document.forms); // All <form> elements
console.log(document.scripts); // All <script> elementsDocument Methods (Preview)
// Find elements (covered in next lesson)
document.getElementById('myId'); // Find by ID
document.querySelector('.myClass'); // Find by CSS selector
document.querySelectorAll('p'); // Find all matching elements
// Create elements (covered later)
document.createElement('div'); // Create new element
document.createTextNode('Hello'); // Create text node
// Write to document (not recommended)
document.write('Hello World'); // Writes to page (avoid in modern code)How JavaScript Interacts with the DOM
The Process
- Browser loads HTML → Creates DOM tree in memory
- JavaScript runs → Can access the DOM
- JavaScript manipulates DOM → Changes structure, content, or style
- Browser updates display → User sees changes
<!DOCTYPE html>
<html>
<head>
<title>DOM Interaction</title>
</head>
<body>
<h1 id="title">Original Title</h1>
<p id="text">Original text</p>
<button id="btn">Change Content</button>
<script>
// 1. Wait for DOM to load
document.addEventListener('DOMContentLoaded', function() {
// 2. Get references to elements
let title = document.getElementById('title');
let text = document.getElementById('text');
let button = document.getElementById('btn');
// 3. Add event listener to button
button.addEventListener('click', function() {
// 4. Modify DOM when button is clicked
title.textContent = 'New Title!';
title.style.color = 'blue';
text.textContent = 'The content has been changed!';
text.style.fontSize = '20px';
});
});
</script>
</body>
</html>Important: JavaScript must wait for the DOM to be fully loaded before trying to access elements. Use DOMContentLoaded event or place scripts at the end of the <body>.
The DOM API
The DOM API is a collection of properties and methods that JavaScript uses to interact with the DOM.
Categories of DOM Operations
1. Selection: Finding elements
document.getElementById('myId')
document.querySelector('.myClass')
document.querySelectorAll('p')2. Manipulation: Changing content and style
element.textContent = 'New text'
element.innerHTML = '<strong>Bold</strong>'
element.style.color = 'red'
element.classList.add('active')3. Creation: Making new elements
document.createElement('div')
element.appendChild(newElement)
element.remove()4. Events: Responding to user actions
element.addEventListener('click', function() {
console.log('Clicked!');
});DOM vs HTML Source Code
DOM can be different from HTML source
HTML Source
<!-- HTML Source Code (static) -->
<!DOCTYPE html>
<html>
<body>
<div id="container">
<p>Hello</p>
</div>
</body>
</html>
<!-- This is what you write -->
<!-- Saved in your .html file -->
<!-- Doesn't change on its own -->DOM (In Memory)
<!-- DOM (dynamic, in memory) -->
<!-- Browser creates DOM from HTML -->
<!-- JavaScript can modify the DOM -->
<script>
// Add new element to DOM
let div = document.getElementById('container');
let newPara = document.createElement('p');
newPara.textContent = 'World';
div.appendChild(newPara);
// DOM now has 2 paragraphs
// But HTML source still shows 1
</script>Key Difference: The HTML source code is what you write. The DOM is what the browser creates and maintains in memory. JavaScript changes the DOM, not the HTML file.
Practical Examples
Example 1: Simple DOM Inspection
<!DOCTYPE html>
<html>
<head>
<title>DOM Inspection</title>
</head>
<body>
<h1>My Website</h1>
<div id="content">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>
<script>
// Inspect document
console.log('Title:', document.title);
console.log('URL:', document.URL);
// Access body
console.log('Body element:', document.body);
console.log('Body tag name:', document.body.tagName);
// Count elements
let paragraphs = document.getElementsByTagName('p');
console.log('Number of paragraphs:', paragraphs.length);
// Get specific element
let content = document.getElementById('content');
console.log('Content div:', content);
console.log('Content children:', content.children.length);
// Tree structure
console.log('First child of body:', document.body.firstChild);
console.log('Last child of body:', document.body.lastChild);
</script>
</body>
</html>Example 2: Understanding Parent-Child Relationships
<!DOCTYPE html>
<html>
<body>
<div id="parent">
<p id="child1">First child</p>
<p id="child2">Second child</p>
<p id="child3">Third child</p>
</div>
<script>
let parent = document.getElementById('parent');
let child2 = document.getElementById('child2');
// Accessing children from parent
console.log('Parent has children:', parent.children.length);
console.log('First child:', parent.firstElementChild.textContent);
console.log('Last child:', parent.lastElementChild.textContent);
// Accessing parent from child
console.log('Child2 parent:', child2.parentElement.id);
// Accessing siblings
console.log('Child2 previous sibling:', child2.previousElementSibling.id);
console.log('Child2 next sibling:', child2.nextElementSibling.id);
// Loop through children
console.log('\nAll children:');
for (let child of parent.children) {
console.log('- ' + child.textContent);
}
</script>
</body>
</html>DOM Fundamentals Visualization
Understanding DOM structure and concepts
console.log() to see your output in the console above.Key Takeaways
- The DOM is a tree-like representation of an HTML document
- It's created by the browser when an HTML page loads
- JavaScript uses the DOM API to interact with HTML
- Everything in the DOM is a node (elements, text, comments, etc.)
- The
documentobject is the entry point to the DOM - HTML elements are organized in a parent-child hierarchy
- DOM changes are in memory—they don't modify the HTML file
- JavaScript must wait for DOM to load before accessing elements
- The DOM enables dynamic, interactive web pages
- Understanding the DOM is essential for web development
What's Next?
You now understand the fundamentals of the DOM—what it is, how it's structured, and how JavaScript interacts with it! This foundation is crucial for everything that follows in DOM manipulation.
In the next lesson, we'll explore Selecting Elements—learning how to find and access specific HTML elements using methods like getElementById(), querySelector(), and more. This is where you'll start actually manipulating web pages!
💪 Practice Challenge:
Before moving on, try creating:
- Open your browser's DevTools and inspect the DOM tree of any website
- Console log
document.bodyand explore its properties - Create an HTML file and use
console.log()to inspect the document object - Draw out the DOM tree structure of a simple HTML page
- Identify parent, child, and sibling relationships in a webpage