Tutorial 5: DOM Manipulation and Event Handling in JavaScript
What is the DOM (Document Object Model)?
The Document Object Model (DOM) is a representation of the structure of an HTML document. JavaScript uses the DOM to interact with and manipulate web pages dynamically. It treats the HTML as a tree of nodes where each element, attribute, and piece of text is a node.
Why is the DOM Important?
- Allows JavaScript to change HTML elements and their content.
- Enables dynamic updates like adding or removing elements.
- Facilitates interaction with user inputs (e.g., button clicks, form submissions).
Example:
Consider this HTML:
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Welcome to JavaScript!</h1>
</body>
</html>
With JavaScript, you can change the <h1> content:
document.getElementById("title").textContent = "Hello, World!";
Selecting Elements in the DOM
JavaScript provides multiple ways to select elements in the DOM for manipulation.
Methods for Selecting Elements:
- getElementById ( ) : Selects an element by its id.
let title = document.getElementById("title");
console.log(title.textContent); // Output: Welcome to JavaScript!
- querySelector ( ) : Selects the first element matching a CSS selector.
let title = document.querySelector("#title");
- querySelectorAll ( ): Selects all elements matching a CSS selector and returns a NodeList.
let items = document.querySelectorAll("li");
items.forEach(item => console.log(item.textContent));
- getElementsByClassName ( ): Selects all elements with a specific class name.
let buttons = document.getElementsByClassName("btn");
- getElementsByTagName ( ) : Selects all elements with a specific tag name.
let paragraphs = document.getElementsByTagName("p");
Questions & Answers:
- Q: How do you select an element by its id ?
- A: Use getElementById ( "id" ) .
- Q: What is the difference between querySelector and querySelectorAll ?
- A: querySelector selects the first matching element, while querySelectorAll selects all matching elements.
- A: querySelector selects the first matching element, while querySelectorAll selects all matching elements.
Changing Content and Styles
JavaScript can dynamically update the content and appearance of elements.
Changing Content:
- textContent : Updates the text inside an element.
document.getElementById("title").textContent = "JavaScript Rocks!";
- innerHTML : Updates the HTML inside an element.
document.getElementById("title").innerHTML = "<span>JavaScript is Fun!</span>";
Changing Styles:
Use the styple property to modify CSS dynamically.
let title = document.getElementById("title");
title.style.color = "blue";
title.style.fontSize = "24px";
Questions & Answers:
- Q: What is the difference between textContent and innerHTML ?
- A: textContent sets plain text, while innerHTML allows adding HTML content.
- Q: How do you change an element’s font size dynamically?
- A: Use the style.fontSize property, e.g., element.style.fontSize = "20px";
Handling Events
Events are actions or occurrences detected by the browser (e.g., clicks, keypresses, mouse movements). JavaScript allows you to attach code to run when these events occur.
Adding Event Listeners:
- Use addEventListener to attach an event handler to an element.
let button = document.getElementById("click-me");
button.addEventListener("click", function () {
alert("Button Clicked!");
});
Common Event Types:
- click : Triggered when an element is clicked.
- mouseover : Triggered when the mouse moves over an element.
- keydown : Triggered when a key is pressed.
Example: Change Color on Click:
let box = document.getElementById("color-box");
box.addEventListener("click", function () {
box.style.backgroundColor = "yellow";
});
Questions & Answers:
- Q: What is an event listener in JavaScript?
- A: A function that waits for a specific event to occur, like a click or keypress.
- Q: How do you attach a click event to a button?
A: Use addEventListener ("click", callback) on the button element.
Mini-Project: Interactive Button
Objective: Create a button that changes the background color of the webpage every time it’s clicked.
HTML:
<!DOCTYPE html>
<html>
<body>
<button id="color-button">Change Background</button>
<script src="script.js"></script>
</body>
</html>
JavaScript
let button = document.getElementById("color-button");
button.addEventListener("click", function () {
let randomColor = `rgb(${Math.floor(Math.random() * 256)},
${Math.floor(Math.random() * 256)},
${Math.floor(Math.random() * 256)})`;
document.body.style.backgroundColor = randomColor;
});
Practice Challenge: To-Do List
Objective: Create a program where users can add tasks to a list and mark them as complete.
HTML:
<!DOCTYPE html>
<html>
<body>
<h1>To-Do List</h1>
<input id="task-input" type="text" placeholder="Enter a task">
<button id="add-button">Add Task</button>
<ul id="task-list"></ul>
<script src="todo.js"></script>
</body>
</html>
JavaScript:
let addButton = document.getElementById("add-button");
let taskInput = document.getElementById("task-input");
let taskList = document.getElementById("task-list");
addButton.addEventListener("click", function () {
let taskText = taskInput.value;
if (taskText !== "") {
let listItem = document.createElement("li");
listItem.textContent = taskText;
listItem.addEventListener("click", function () {
listItem.style.textDecoration = "line-through";
});
taskList.appendChild(listItem);
taskInput.value = ""; // Clear input
}
});
Conclusion
Recap:
- The DOM lets JavaScript interact with HTML and CSS.
- You can select elements using methods like getElementById or querySelector.
- Event handling allows you to respond to user actions dynamically.
Next Steps: In the next tutorial, we’ll learn about APIs and Fetch, which enable your JavaScript to interact with external data sources.
Questions for Recap:
- Q: How do you dynamically change the text of an element?
- A: Use element.textContent = "New Text" ; .
- Q: What does the addEventListener method do?
- A: It attaches an event listener to an element to respond to specific events