The Document Object Model (DOM) is the way browsers represent a web page internally. It acts as a tree-like structure that models every part of an HTML document, allowing JavaScript to access, modify, and interact with the page dynamically.
Imagine your HTML document as a big family tree. At the top is the root, and branches grow down into smaller branches and leaves. Similarly, the DOM tree starts from the document
root node and branches out into elements like <html>
, <body>
, <div>
, and more.
Each node in this tree represents a part of the document:
<div>
, <p>
, <img>
. They can contain other nodes, including child elements or text.When a browser loads an HTML page, it reads the HTML code from top to bottom and creates the DOM tree node by node:
<html>
<body>
<h1>Welcome</h1>
<p>Hello, world!</p>
</body>
</html>
This HTML creates a DOM tree like this:
document
└─ html
└─ body
├─ h1
│ └─ "Welcome" (text node)
└─ p
└─ "Hello, world!" (text node)
This hierarchical tree structure lets JavaScript navigate and manipulate any part of the page easily. For example, you can find the <p>
element inside <body>
, change its text, add new elements, or remove existing ones—all by moving through this tree.
Think of the DOM as the living blueprint of your web page—a dynamic representation that your scripts can explore and update in real time.
Understanding the DOM tree is the first step toward mastering how web pages work behind the scenes and interact with your JavaScript code!
getElementById
, querySelector
)To interact with a webpage’s content, JavaScript needs to select or query elements from the DOM tree. Two of the most common ways to find elements are using getElementById
and querySelector
.
getElementById
id
attribute.document.getElementById('elementId')
null
if no element matches.Example:
<div id="main-header">Welcome!</div>
const header = document.getElementById('main-header');
console.log(header.textContent); // Output: Welcome!
querySelector
and querySelectorAll
Purpose: Select elements using CSS selectors.
Syntax:
document.querySelector(selector)
— returns the first matching element.document.querySelectorAll(selector)
— returns all matching elements as a static NodeList.Returns: Single element (or null
) for querySelector
, and a NodeList for querySelectorAll
.
Performance: Slightly slower than getElementById
but very flexible.
Examples:
<ul>
<li class="item">Apple</li>
<li class="item">Banana</li>
<li class="item">Cherry</li>
</ul>
const firstItem = document.querySelector('.item');
console.log(firstItem.textContent); // Output: Apple
const allItems = document.querySelectorAll('.item');
allItems.forEach(item => console.log(item.textContent));
// Output:
// Apple
// Banana
// Cherry
Feature | getElementById |
querySelector / querySelectorAll |
---|---|---|
Selects by | Unique id |
Any CSS selector |
Returns | Single element or null |
Single element (querySelector ) or NodeList (querySelectorAll ) |
Use case | Fast, simple ID selection | Flexible, complex selections (classes, tags, attributes, combinations) |
Performance | Faster for ID-based queries | Slightly slower but usually negligible |
"footer"
and change its background color:const footer = document.getElementById('footer');
footer.style.backgroundColor = 'lightblue';
"btn"
and disable it:const firstBtn = document.querySelector('.btn');
firstBtn.disabled = true;
"content"
and log their text:const paragraphs = document.querySelectorAll('#content p');
paragraphs.forEach(p => console.log(p.textContent));
getElementById
for fast, straightforward access to elements by ID.querySelector
and querySelectorAll
for flexible, CSS-based selections.Mastering element querying sets the foundation for dynamic web page interactions!
Once you've selected elements from the DOM, the next step is to modify them to change how your webpage looks or behaves. You can update an element’s content, attributes, styles, or classes—all in real time using JavaScript.
To update the visible text inside an element, use:
.textContent
— sets or gets the plain text inside an element..innerHTML
— sets or gets HTML content (including tags) inside an element.Example:
<p id="message">Hello, world!</p>
const message = document.getElementById('message');
// Change text content (safe, no HTML interpreted)
message.textContent = 'Welcome to JavaScript!';
// Or update HTML content (can include tags)
message.innerHTML = 'Welcome to <strong>JavaScript</strong>!';
You can change CSS styles directly via the .style
property.
Example:
message.style.color = 'blue';
message.style.fontWeight = 'bold';
message.style.backgroundColor = '#f0f0f0';
This immediately updates the paragraph's color, weight, and background.
Classes control CSS styling and can be easily manipulated with the classList
property:
.classList.add('className')
— adds a class.classList.remove('className')
— removes a class.classList.toggle('className')
— toggles a class on/offExample:
message.classList.add('highlight');
message.classList.remove('highlight');
message.classList.toggle('highlight'); // Adds if missing, removes if present
Attributes like src
(images), href
(links), alt
, or title
can be changed with:
.setAttribute(attributeName, value)
.getAttribute(attributeName)
element.href = '...'
)Example:
<a id="myLink" href="https://example.com">Visit Example</a>
<img id="myImage" src="image1.jpg" alt="Image">
const link = document.getElementById('myLink');
const image = document.getElementById('myImage');
link.setAttribute('href', 'https://openai.com');
link.textContent = 'Visit OpenAI';
image.src = 'image2.jpg';
image.alt = 'New Image';
All these modifications instantly update the page without needing to reload it. This dynamic behavior is what makes web apps interactive and responsive to user input.
.textContent
or .innerHTML
to change element content..style
..classList
methods to manage CSS classes cleanly..setAttribute
or direct properties.Mastering DOM modifications lets you bring your web pages to life with JavaScript!
Manipulating the DOM isn't limited to modifying existing elements — you can also create new elements dynamically and remove elements when they are no longer needed. This ability is essential for building interactive, dynamic web pages.
document.createElement
To create a new element, use the document.createElement
method:
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello, I am a new div!';
At this point, newDiv
exists only in memory — it’s not yet visible on the page.
To insert your new element into the document, you attach it to an existing element using methods like:
appendChild()
— adds the new element as the last child.insertBefore()
— inserts the new element before a specific existing child.Example: Add a new item to a list
<ul id="todoList">
<li>Buy groceries</li>
<li>Walk the dog</li>
</ul>
const list = document.getElementById('todoList');
const newItem = document.createElement('li');
newItem.textContent = 'Read a book';
// Add new item to the end of the list
list.appendChild(newItem);
const secondItem = list.children[1]; // The second <li>
const urgentItem = document.createElement('li');
urgentItem.textContent = 'Pay bills';
// Insert urgentItem before secondItem
list.insertBefore(urgentItem, secondItem);
There are two common ways to remove elements:
removeChild()
method:const firstItem = list.children[0];
list.removeChild(firstItem);
remove()
method (modern browsers):const lastItem = list.lastElementChild;
lastItem.remove();
Imagine a simple to-do app where users can add and remove tasks dynamically.
// Add task
function addTask(text) {
const li = document.createElement('li');
li.textContent = text;
list.appendChild(li);
}
// Remove first task
function removeFirstTask() {
if (list.firstElementChild) {
list.firstElementChild.remove();
}
}
addTask('Learn DOM manipulation');
removeFirstTask();
document.createElement()
to create new DOM elements.appendChild()
or insertBefore()
.removeChild()
from the parent or the element’s own remove()
method.By mastering creation and removal, you control the structure and content of your web pages dynamically!