DOM Manipulation
What is the DOM?
The DOM (Document Object Model) is the browser's live representation of your HTML page as a tree of JavaScript objects. Every element on your page — every heading, paragraph, button, and link — is a node in this tree.
When you change the DOM with JavaScript, the browser immediately updates what the user sees. This is how JavaScript makes pages interactive.
Selecting elements
Before you can change an element, you need to select it. The two most important methods:
querySelector — selects the first element that matches a CSS selector:JavaScript
const title = document.querySelector("h1");
const btn = document.querySelector(".submit-btn");
const form = document.querySelector("#signup-form");querySelectorAll — selects all matching elements (returns a NodeList):JavaScript
const allParagraphs = document.querySelectorAll("p");
allParagraphs.forEach((p) => {
p.style.color = "#333";
});Changing content and attributes
JavaScript
const heading = document.querySelector("h1");
heading.textContent = "New Title";
heading.innerHTML = "New <em>Title</em>"; // Can include HTML
heading.setAttribute("id", "main-heading");
heading.classList.add("highlighted");
heading.classList.remove("hidden");
heading.classList.toggle("active");textContent is safer than innerHTML because it doesn't parse HTML (preventing XSS vulnerabilities).Listening for events
Events are things that happen on the page — clicks, key presses, form submissions, scrolling. You respond to them with event listeners:
JavaScript
const button = document.querySelector("#my-button");
button.addEventListener("click", () => {
console.log("Button was clicked!");
});Common events:
| Event | When it fires |
|---|---|
click | User clicks an element |
input | User types in a text field |
submit | A form is submitted |
keydown | A key is pressed |
mouseover | Mouse enters an element |
A practical example: counter
Here's a complete example that ties it all together:
HTML
<p>Count: <span id="count">0</span></p>
<button id="increment">+1</button>
<button id="reset">Reset</button>JavaScript
let count = 0;
const display = document.querySelector("#count");
document.querySelector("#increment").addEventListener("click", () => {
count += 1;
display.textContent = count;
});
document.querySelector("#reset").addEventListener("click", () => {
count = 0;
display.textContent = count;
});This pattern — select element, listen for event, update DOM — is the foundation of almost every interactive feature on the web.
Creating and removing elements
JavaScript
const list = document.querySelector("#todo-list");
const newItem = document.createElement("li");
newItem.textContent = "Buy groceries";
list.appendChild(newItem);
newItem.remove();Key takeaway
The DOM is how JavaScript talks to the page. Master
querySelector, addEventListener, and textContent, and you can build any interactive feature. Start small — build a counter, a toggle, a form validator — and the patterns will click.