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:
- Select elements using
getElementByIdandquerySelector. - Change text, HTML, and CSS styles via JS.
- Add Event Listeners for clicks and keyboard input.
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.
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.
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
- Create 3 buttons: Red, Blue, Green.
- When a button is clicked, change a `div` box's color to the respective color.
- Display the name of the current color inside the box.
Step-by-Step Process
- Select the buttons and the box element.
- Use
addEventListeneron each button. - Change
style.backgroundColorandinnerTextinside the listener.
Expected Deliverables
switcher.htmlandscript.js.