DOM Manipulation: When Code Starts Moving the Page
This is where JavaScript stops being theory
and starts touching the screen.
βClick. Change. React. Welcome to real front-end life.β
π³ What Is the DOM?
DOM stands for Document Object Model. In simple terms:
- The browser turns HTML into a tree of objects
- JavaScript can access and control every branch
HTML
<h1>Hello</h1>
How JavaScript sees it:
document β h1 β "Hello"
π― Selecting HTML Elements
π querySelector()
The most-used DOM weapon.
JavaScript
const title = document.querySelector("h1");
const card = document.querySelector(".card");
const button = document.querySelector("#btn");
π getElementById()
Fast, simple, ID only.
JavaScript
const submitButton = document.getElementById("submitBtn");
βοΈ Editing Content
Change text:
JavaScript
title.textContent = "Hello DOM π";
Inject HTML:
JavaScript
title.innerHTML = "Hi";
π¨ classList & Style
Class control:
JavaScript
title.classList.add("active");
title.classList.remove("active");
title.classList.toggle("active");
Inline style (demo only):
JavaScript
title.style.color = "red";
title.style.fontSize = "32px";
Real projects prefer CSS classes.
β‘ Event Listeners
Events are the bridge between users and JavaScript.
JavaScript
button.addEventListener("click", () => {
alert("Button clicked!");
});
JavaScript
form.addEventListener("submit", (e) => {
e.preventDefault();
console.log("Form submitted");
});
π§± Creating Elements Dynamically
JavaScript
const li = document.createElement("li");
li.textContent = "New item";
list.appendChild(li);
This is the core of todo apps, product lists, feeds β everything.
β Mini Project β Todo App
JavaScript
const input = document.querySelector("#todoInput");
const btn = document.querySelector("#addBtn");
const list = document.querySelector("#todoList");
btn.addEventListener("click", () => {
const li = document.createElement("li");
li.textContent = input.value;
list.appendChild(li);
input.value = "";
});
Click β item appears. Instant dopamine.
π Mini Project β Light / Dark Mode
JavaScript
toggle.addEventListener("click", () => {
document.body.classList.toggle("dark");
});
One click. One vibe.
π’ Mini Project β Counter
JavaScript
let count = 0;
btn.addEventListener("click", () => {
count++;
display.textContent = count;
});
π₯ Mini Challenges
- Todo: click to strike-through, double click to delete
- Counter: add minus button + max/min limit
- Theme: save mode in localStorage