Intermediate Level • Lesson 4

🌐 DOM Manipulation

⏱️ 45 minutes 📚 Intermediate 🎯 Web Development
🚀

Build Interactive Websites!

Combine HTML, CSS, and JavaScript to create awesome web experiences!

HTML + CSS + JavaScript = Interactive Web!

You've learned JavaScript - now let's connect it to web pages! Websites need all three technologies working together:

🏗️ The Web Technology Stack

  • HTML: Structure and content (the skeleton)
  • CSS: Styling and layout (the appearance)
  • JavaScript: Interactivity and behavior (the brain)

Analogy: Think of a house - HTML is the structure, CSS is the paint and decoration, JavaScript is the electricity that makes things work!

💡 Real Example: When you click "Like" on Instagram, JavaScript detects your click, updates the number, and changes the heart color!

Key Concepts

🌳

DOM

Document Object Model - JavaScript's way to access HTML elements.

🖱️

Event Listeners

Detect user actions like clicks, keypresses, and mouse movements.

🎯

getElementById

Find specific HTML elements by their ID to manipulate them.

✏️

innerHTML

Change the content inside HTML elements dynamically.

🎨

style Property

Change CSS styles of elements using JavaScript.

⌨️

User Input

Get data from text boxes and forms to use in programs.

Accessing HTML Elements

🎯 Finding Elements with JavaScript

HTML:

<h1 id="greeting">Hello!</h1> <button id="changeBtn">Click Me</button>

JavaScript:

// Get elements by ID let heading = document.getElementById("greeting"); let button = document.getElementById("changeBtn"); // Change the text heading.innerHTML = "Selamat datang!";

Result: The heading text changes from "Hello!" to "Selamat datang!"

Event Listeners - Responding to Clicks

🖱️ Click Events

HTML:

<button id="myButton">Click Me!</button> <p id="message"></p>

JavaScript:

let button = document.getElementById("myButton"); let message = document.getElementById("message"); button.addEventListener("click", function() { message.innerHTML = "You clicked the button!"; });

How it works: addEventListener waits for a click, then runs the function!

Interactive Demo - Try It!

🎮 Live Button Example

Changing Styles with JavaScript

🎨 Dynamic Styling

HTML:

<div id="box">I'm a box!</div> <button id="colorBtn">Change Color</button>

JavaScript:

let box = document.getElementById("box"); let colorBtn = document.getElementById("colorBtn"); colorBtn.addEventListener("click", function() { box.style.backgroundColor = "blue"; box.style.color = "white"; box.style.padding = "20px"; });

Getting User Input

📝 Text Input Example

HTML:

<input type="text" id="nameInput" placeholder="Enter your name"> <button id="greetBtn">Greet Me</button> <p id="greeting"></p>

JavaScript:

let nameInput = document.getElementById("nameInput"); let greetBtn = document.getElementById("greetBtn"); let greeting = document.getElementById("greeting"); greetBtn.addEventListener("click", function() { let name = nameInput.value; // Get the input value greeting.innerHTML = "Hello, " + name + "!"; });

Keyboard Events

⌨️ Detecting Key Presses

let input = document.getElementById("myInput"); input.addEventListener("keypress", function(event) { if (event.key === "Enter") { console.log("You pressed Enter!"); } });

Common events: "keypress", "keydown", "keyup"

Project Example: Simple Counter

🔢 Click Counter

HTML:

<h2>Click Counter</h2> <p id="count">0</p> <button id="increaseBtn">Increase</button> <button id="resetBtn">Reset</button>

JavaScript:

let count = 0; let countDisplay = document.getElementById("count"); document.getElementById("increaseBtn").addEventListener("click", function() { count = count + 1; countDisplay.innerHTML = count; }); document.getElementById("resetBtn").addEventListener("click", function() { count = 0; countDisplay.innerHTML = count; });

Malaysian Quiz Game Example

🇲🇾 Simple Quiz

<h3>What is the capital of Malaysia?</h3> <button id="kl">Kuala Lumpur</button> <button id="penang">Penang</button> <p id="result"></p> <script> document.getElementById("kl").addEventListener("click", function() { document.getElementById("result").innerHTML = "Correct! 🎉"; document.getElementById("result").style.color = "green"; }); document.getElementById("penang").addEventListener("click", function() { document.getElementById("result").innerHTML = "Try again!"; document.getElementById("result").style.color = "red"; }); </script>

Common Mistakes to Avoid

⚠️ Watch Out For:

  • Wrong IDs: Make sure HTML id matches getElementById!
  • Script timing: Put JavaScript after HTML or use DOMContentLoaded
  • Forgetting .value: Use .value to get input text, not .innerHTML
  • Missing quotes: Event names need quotes: "click" not click

Summary

You've learned:

  • ✅ The DOM (Document Object Model) is how JavaScript talk to HTML
  • ✅ getElementById() finds specific HTML elements
  • ✅ querySelector() uses CSS rules to find elements
  • ✅ .innerHTML and .textContent change what elements say
  • ✅ .style changes how elements look (CSS)
  • ✅ addEventListener() makes elements respond to clicks and typing

🎮 Interactive Challenge: Try These Live Demos!

Play with these interactive examples, then create your own:

📊 Live Demo: Click Counter

0

Try it! Click the buttons to see the counter change in real-time.

👋 Live Demo: Name Greeter

🎨 Live Demo: Background Color Changer

Click any color button to change this demo's background!

💡 Challenge: Look at the code below and try to build similar demos yourself!

📝 Code Example: Name Greeter

Here's how the Name Greeter demo works:

<!DOCTYPE html> <html> <head> <title>Name Greeter</title> </head> <body> <h1>Enter Your Name</h1> <input type="text" id="nameBox" placeholder="Your name"> <button id="greetButton">Greet Me</button> <p id="output"></p> <script> // Your JavaScript code here! </script> </body> </html>

🎨 Challenge 2: Color Changer

Create buttons that change the background color:

<button id="redBtn">Red</button> <button id="blueBtn">Blue</button> <button id="greenBtn">Green</button> <script> // Add event listeners to change document.body.style.backgroundColor </script>

💰 Challenge 3: Simple Calculator

Build a basic addition calculator:

<input type="number" id="num1" placeholder="First number"> <input type="number" id="num2" placeholder="Second number"> <button id="addBtn">Add</button> <p id="result"></p> <script> // Get values, add them, display result </script>
💡 Pro Tip: Save your HTML file and open it in a browser to test your interactive projects!

🎯 Project Activity: Malaysian Culture Quiz

What You'll Build:

Create an interactive quiz about Malaysian culture, food, and places!

Instructions:

  1. Create an HTML file with quiz questions
  2. Add buttons for answer choices
  3. Use JavaScript to check answers and keep score
  4. Display results with colors (green for correct, red for wrong)
  5. Add a "Next Question" button to move through questions

Example Quiz Question:

<h2>Question 1: What is Malaysia's national flower?</h2> <button class="answer" id="hibiscus">Hibiscus</button> <button class="answer" id="orchid">Orchid</button> <button class="answer" id="jasmine">Jasmine</button> <p id="feedback"></p> <p id="score">Score: 0</p>

Quiz Topics to Include:

  • Malaysian foods (Nasi Lemak, Roti Canai, etc.)
  • Famous places (KLCC, Batu Caves, Penang, etc.)
  • Malaysian culture and traditions
  • Languages spoken in Malaysia
  • Malaysian festivals (Hari Raya, CNY, Deepavali)
🏆 Bonus Features: Add a timer, sound effects, or animations to make it more fun!

💪 Practice Challenges

Challenge 1: E-Wallet Calculator

Create a simple e-wallet balance tracker:

  • Display current balance
  • Button to add money
  • Button to spend money
  • Input field for amount
  • Update balance display after each transaction

Hint: Start with balance = 100.00

Challenge 2: BMI Calculator

Build a Body Mass Index calculator:

  • Input for weight (kg)
  • Input for height (cm)
  • Button to calculate BMI
  • Display BMI result with category (Underweight, Normal, Overweight)

Formula: BMI = weight / (height in meters)²

Challenge 3: Random Number Game

Create a guessing game:

  • Computer picks a random number 1-10
  • User enters a guess
  • Show "Too high", "Too low", or "Correct!"
  • Keep track of number of attempts

Hint: Use Math.random() for random numbers

Challenge 4: To-Do List

Build a simple task list:

  • Input field to enter tasks
  • Button to add task to list
  • Display all tasks
  • Button to clear all tasks

Extra: Add ability to mark tasks as complete!

Challenge 5: Traffic Light Simulator

Create an interactive traffic light:

  • Three colored circles (red, yellow, green)
  • Buttons to change which light is on
  • Only one light can be on at a time
  • Change circle colors using style.backgroundColor

Challenge: Add automatic cycling every 3 seconds!