Chapter 5 — JS DOM Manipulation

📚 Chapter Overview

This is where the magic happens. In this chapter, you will learn how JavaScript interacts with HTML and CSS using the Document Object Model (DOM) to change content, styles, and handle user events dynamically.

Learning Objectives:

5.1 Selecting & Modifying Elements

Part 1 — Definition

The **DOM** is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. You first "Find" the element, then you "Action" it.

Part 2 — Syntax

let title = document.getElementById("main-title");
title.innerText = "New Title";
title.style.color = "red";

Part 3 — Example

Problem: Change the background of a div when a button is clicked.

script.js
function changeBg() {
    document.body.style.backgroundColor = "yellow";
}

Observation: innerText changes only the text, while innerHTML can inject new HTML tags.

Part 4 — Video

Video: Coming Soon


5.2 Events and Listeners

Part 1 — Definition

An Event is an action that happens on your web page, like a user clicking a button or typing in a field. An Event Listener is a function that "waits" for that event to happen and then runs a specific piece of code.

Part 2 — Syntax

button.addEventListener("click", () => {
    console.log("Button Clicked!");
});

Part 3 — Example

Problem: Create a "Toggle" button that shows/hides a paragraph.

script.js
let btn = document.querySelector("#toggle-btn");
let content = document.querySelector("#content");

btn.addEventListener("click", () => {
    if (content.style.display === "none") {
        content.style.display = "block";
    } else {
        content.style.display = "none";
    }
});

Part 4 — Video

Video: Coming Soon


🏆 Chapter Challenge

Challenge Objective

Build a "Interactive Color Switcher".

Requirements

Step-by-Step Process

  1. Select the buttons and the box element.
  2. Use addEventListener on each button.
  3. Change style.backgroundColor and innerText inside the listener.

Expected Deliverables

Solve in Editor