JavaScript Roadmap — Day 16: DOM Manipulation

 

JavaScript · Day 16 of 180 · Beginner Phase

DOM Manipulation

DOM Manipulation is where JavaScript gets visual. This is how you make websites interactive — clicking buttons, showing popups, changing colors, adding items to lists. Everything you see happening on a webpage is DOM manipulation.

Day 16 / 180
Beginner Phase
🕐 15 min read
💻 7 code examples
🎯 3 practice tasks

Think about everything that happens when you use a website:

🌙 Click dark mode button → page changes color
🛒 Click Add to Cart → counter increases
Submit a form → success message appears
🔍 Type in search box → results filter in real time
Click close button → popup disappears

Every single one of those interactions is JavaScript manipulating the DOM. Until now you have been writing JavaScript that only runs in the console. Today — for the first time — your code will actually change what users see on screen. This is the lesson where JavaScript becomes truly exciting.

1. What is the DOM?

The Document Object Model (DOM) is the browser's representation of your HTML as a tree of objects. When a browser loads an HTML page — it converts every element into a JavaScript object that you can read and modify. The document object is your gateway to the entire page:

HTML → DOM Tree
/* Your HTML */
<html>
  <body>
    <h1 id="title">Hello World</h1>
    <button id="btn">Click Me</button>
  </body>
</html>

/* Browser converts it to objects */
document            // the entire page
document.body       // the body element
document.title      // page title
document.URL        // current URL

// You can change ANYTHING through the DOM
document.title = "WaheedBlog"; // changes browser tab title!

2. Selecting Elements — Finding HTML in JS

Before you can change anything — you need to select it. JavaScript gives you several methods to find elements. querySelector is the modern standard and works exactly like CSS selectors:

JavaScript — Selecting Elements
// querySelector — first matching element (modern ✅)
const title  = document.querySelector("#title");     // by id
const btn    = document.querySelector(".btn");       // by class
const para   = document.querySelector("p");          // by tag
const input  = document.querySelector("input[type='email']"); // by attr
const nested = document.querySelector(".card .title"); // nested

// querySelectorAll — ALL matching elements
const allBtns  = document.querySelectorAll("button");
const allCards = document.querySelectorAll(".card");

// Loop over all selected elements
allBtns.forEach(btn => {
  btn.style.color = "blue";
});

// Older methods — still used
document.getElementById("title");         // by id only
document.getElementsByClassName("card");   // HTMLCollection
document.getElementsByTagName("p");       // HTMLCollection

3. Changing Content & Attributes

Once you have selected an element you can change its text, HTML content, and attributes. This is how you dynamically update what users see:

JavaScript — Changing Content
const title = document.querySelector("#title");

// textContent — plain text only (safe)
title.textContent = "Welcome to WaheedBlog!";
console.log(title.textContent); // "Welcome to WaheedBlog!"

// innerHTML — can include HTML tags
title.innerHTML = "Welcome to <span style='color:blue'>WaheedBlog</span>!";

// Change attributes
const img = document.querySelector("img");
img.setAttribute("src", "new-image.jpg");
img.setAttribute("alt", "Profile photo");
console.log(img.getAttribute("src")); // "new-image.jpg"

// Change input value
const input = document.querySelector("#email");
input.value = "waheed@gmail.com";
console.log(input.value);

// href, src, id — direct properties
const link = document.querySelector("a");
link.href = "https://waheedblog.online";
link.textContent = "Visit WaheedBlog";

4. Modifying Styles & Classes

You can change CSS styles directly through JavaScript. The modern and preferred approach is to add and remove CSS classes rather than setting inline styles — this keeps your styling in CSS where it belongs:

JavaScript — Styles & Classes
const box = document.querySelector(".box");

// Direct style — camelCase property names
box.style.backgroundColor = "#4f6ef7";
box.style.color            = "white";
box.style.padding          = "20px";
box.style.borderRadius     = "12px";
box.style.display          = "none";  // hide element

// classList — modern and preferred ✅
box.classList.add("active");       // add class
box.classList.remove("hidden");    // remove class
box.classList.toggle("dark");      // toggle on/off
box.classList.contains("active"); // true/false
box.classList.replace("old", "new"); // replace class

// Dark mode toggle — real world example
const body = document.body;
function toggleDarkMode() {
  body.classList.toggle("dark-mode");
  const isDark = body.classList.contains("dark-mode");
  console.log(isDark ? "Dark mode ON" : "Dark mode OFF");
}
Pro Tip #1 — classList over inline styles
Always prefer classList.add/remove/toggle over setting element.style directly. Define your visual states in CSS classes — JavaScript just switches between them. This separation of concerns is how professional frontend developers work.
Pro Tip #2 — toggle is perfect for on/off states
classList.toggle() adds the class if it is not there — removes it if it is. This single method handles dark mode, menu open/close, accordion expand/collapse, and any other binary state. It is one of the most used DOM methods in real projects.

5. Event Listeners — Making Pages Interactive 🔥

Events are things that happen in the browser — clicks, key presses, form submissions, mouse movements. addEventListener lets you run code when these events happen. This is the heart of all interactivity:

JavaScript — Event Listeners
const btn = document.querySelector("#btn");

// Basic click event
btn.addEventListener("click", function() {
  console.log("Button clicked!");
});

// Arrow function — cleaner
btn.addEventListener("click", () => {
  btn.textContent = "Clicked! ✅";
  btn.style.background = "#00c896";
});

// Event object — information about the event
btn.addEventListener("click", (event) => {
  console.log(event.target);      // element that was clicked
  console.log(event.type);        // "click"
  console.log(event.clientX);    // mouse X position
});

// Common events
input.addEventListener("input",  (e) => console.log(e.target.value));
input.addEventListener("focus",  () => input.classList.add("focused"));
input.addEventListener("blur",   () => input.classList.remove("focused"));
form.addEventListener("submit", (e) => {
  e.preventDefault(); // stop page reload!
  console.log("Form submitted");
});
document.addEventListener("keydown", (e) => console.log(e.key));

6. Create & Remove Elements

You can dynamically create new HTML elements and add them to the page — or remove existing ones. This is how todo lists, chat messages, and product cards are built dynamically:

JavaScript — Create & Remove Elements
// Create a new element
const newDiv = document.createElement("div");
newDiv.textContent = "I am a new element!";
newDiv.classList.add("card");
newDiv.style.padding = "16px";

// Add to page
document.body.appendChild(newDiv);   // add at end
document.body.prepend(newDiv);      // add at beginning

// insertAdjacentHTML — fastest way
const list = document.querySelector("#list");
list.insertAdjacentHTML("beforeend", `
  <li class="item">New Item</li>
`);

// Remove an element
const oldEl = document.querySelector(".old");
oldEl.remove(); // modern way

// Real world — add todo item
function addTodo(text) {
  const li = document.createElement("li");
  li.innerHTML = `
    <span>${text}</span>
    <button onclick="this.parentElement.remove()">❌</button>
  `;
  document.querySelector("#todoList").appendChild(li);
}

7. Real Project — Interactive Counter 🔥

Let us put everything together. Here is a fully working counter app using everything from this lesson — selecting, changing content, event listeners, and class manipulation:

JavaScript — Counter App (HTML + JS)
<!-- HTML -->
<div id="app">
  <h1 id="count">0</h1>
  <button id="dec"></button>
  <button id="reset">Reset</button>
  <button id="inc">+</button>
</div>

// JavaScript
let count = 0;
const countEl = document.querySelector("#count");

function updateDisplay() {
  countEl.textContent = count;
  countEl.style.color =
    count > 0 ? "#00c896" :
    count < 0 ? "#f38ba8" : "#0f1117";
}

document.querySelector("#inc").addEventListener("click", () => {
  count++;
  updateDisplay();
});
document.querySelector("#dec").addEventListener("click", () => {
  count--;
  updateDisplay();
});
document.querySelector("#reset").addEventListener("click", () => {
  count = 0;
  updateDisplay();
});

8. Try It Yourself — Live DOM Playground

This playground has a live preview panel — edit the HTML and JavaScript and click Run to see your changes instantly!

✏️ Live DOM Playground — Day 16
HTML
JAVASCRIPT
LIVE PREVIEW
💡 Edit HTML & JS then click Run!

9. Practice Tasks

Task 1 — Easy: Color Changer

Create a button that changes the background color of a div every time it is clicked. Use an array of colors and cycle through them using a counter. Use classList or style.backgroundColor.

Task 2 — Medium: Todo List

Build a working todo list — an input field and Add button. When clicked — create a new list item with the input text and a Delete button. The Delete button removes that specific item. Clear the input after adding. Show a message when the list is empty.

Task 3 — Hard: Dark Mode Toggle

Build a complete dark mode toggle. Create a page with a header, some text, and a toggle button showing 🌙 or ☀️. When clicked — toggle dark mode on the entire page using classList.toggle. Save the user preference to localStorage so it persists when the page reloads. On page load — read localStorage and apply the saved theme.

Next Lesson
Day 17 — Events & Event Handling — Deep Dive
View Full Roadmap →
Enjoying this roadmap?
Follow Muhammad Waheed Asghar for daily JavaScript tips and updates!

Popular Posts