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

πŸ“Œ Key Takeaways

  • DOM connects JavaScript to HTML
  • querySelector is your main tool
  • Events make pages interactive
  • createElement builds dynamic UI
  • This is the foundation of all front-end frameworks