16.3 DOM Manipulation (20 mins)
Introduction to DOM Manipulation:
DOM Manipulation allows you to dynamically change the content, attributes, and styles of HTML elements using JavaScript. This makes web pages interactive and responsive to user actions.
Common operations for DOM manipulation include:
Modifying Content: Changing the text or HTML inside an element.
Changing Attributes: Modifying or adding attributes like
src,href, oraltfor elements like images or links.Changing Styles: Dynamically altering the appearance of elements by modifying CSS properties.
DOM Manipulation Methods:
Modifying Content:
innerTextandtextContent: Changes the text inside an element.innerHTML: Changes the HTML content of an element, allowing you to insert HTML tags dynamically.Example:
let heading = document.getElementById("title"); heading.innerText = "New Heading Text"; // Changes the text inside the <h1>
Modifying Attributes:
setAttribute(): Adds or changes the value of an element's attribute.getAttribute(): Retrieves the value of an element's attribute.Example:
let image = document.getElementById("myImage"); image.setAttribute("src", "new_image.jpg"); // Changes the image source
Modifying Styles:
styleproperty: Allows you to change CSS styles like color, font size, background color, etc.Example:
let paragraph = document.getElementById("description"); paragraph.style.color = "blue"; // Changes the text color to blue paragraph.style.fontSize = "20px"; // Changes the font size to 20px
Common DOM Manipulation Tasks:
Changing Text Content:
You can change the text of any element using
innerTextortextContent. The difference is thatinnerTextrespects the CSS styles (such asdisplay: none;), whiletextContentreturns all text, even if it's hidden.Example:
let message = document.getElementById("welcomeMessage"); message.innerText = "Welcome, User!"; // Changes the text content
Modifying Element Attributes:
Use
setAttribute()to add or change an element’s attributes (e.g., changing an image's source or a link's destination).Example:
let link = document.getElementById("externalLink"); link.setAttribute("href", "https://www.example.com"); // Changes the link's destination
Changing Styles:
The
styleproperty allows you to modify inline CSS styles directly from JavaScript.Example:
let button = document.getElementById("myButton"); button.style.backgroundColor = "green"; // Changes the button background color button.style.padding = "10px"; // Changes button padding
Student Activity (20 mins):
Objective: Students will practice modifying the content, attributes, and styles of HTML elements using JavaScript.
Step-by-Step Activity:
Create an HTML file (e.g.,
dom_manipulation.html) and write JavaScript code to modify the content, attributes, and styles of elements dynamically.Example Code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DOM Manipulation</title> </head> <body> <h1 id="title">Welcome to My Website</h1> <p id="description">This is a short description of the website.</p> <img id="myImage" src="../../../Solo-mini-project-3/images/hnu-mypic.JPG" alt="Old Image" width="200px" /> <a id="externalLink" href="https://www.google.com">Go to Google</a> <button id="changeContentButton">Change Content</button> <script> // Change the text content of the heading let heading = document.getElementById("title"); heading.innerText = "DOM Manipulation Example"; // Change the description text and style let description = document.getElementById("description"); description.innerText = "This text has been updated using JavaScript!"; description.style.color = "red"; // Change text color to red description.style.fontSize = "18px"; // Change font size // Modify the image source and alt attribute let image = document.getElementById("myImage"); // Modify the link destination let link = document.getElementById("externalLink"); link.setAttribute("href", "https://www.example.com"); // Change the link URL link.innerText = "Go to Example.com"; // Change link text // Change content on button click let button = document.getElementById("changeContentButton"); button.addEventListener("click", function() { heading.innerText = "Content Changed After Button Click!"; description.style.backgroundColor = "lightyellow"; // Change background color image.setAttribute("src", "Silroad Travel Logo.png"); // Change the image source image.setAttribute("alt", "New Image Description"); // Change the alt text }); </script> </body> </html>Run the file in a browser:
Open the HTML file in a browser and see how the text, attributes, and styles are changed.
Click the button and observe how the content dynamically updates when the button is clicked.
Explanation of the Code:
Text Content: The
<h1>element’s text is changed usinginnerText, and the paragraph’s text and style are updated.Attributes: The image's
srcandaltattributes are modified withsetAttribute(), and the link'shrefis changed.Styles: The
styleproperty is used to change the color, font size, and background color dynamically.Event Listener: The button listens for a click event, and when clicked, it modifies the content and background color of the description.
Challenge:
Modify Multiple Elements:
Add a second button that changes the image size and hides the paragraph when clicked.
Example:
let imageButton = document.createElement("button"); imageButton.innerText = "Change Image Size and Hide Paragraph"; document.body.appendChild(imageButton); imageButton.addEventListener("click", function() { image.style.width = "400px"; // Change the image size description.style.display = "none"; // Hide the paragraph });Extra Challenge:
Allow the user to input a new link URL and update the
<a>element'shrefdynamically based on the user's input.
Example:
let userInput = prompt("Enter a new link URL:"); link.setAttribute("href", userInput); link.innerText = "Go to " + userInput;
Extra Challenge:
modify the code so that the image can be toggled between two different images from the
/imagesfolder each time the button is clicked, you can implement a simple toggle mechanism.Store the paths of the two images you want to toggle between.
Use a flag to keep track of which image is currently displayed.
Update the image source based on the flag each time the button is clicked.
Here's the modified code:
// Image Toggle Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Toggle Example</title>
</head>
<body>
<h1 id="heading">Original Heading</h1>
<p id="description">This is the original description.</p>
<img id="image" src="/images/image1.png" alt="Original Image Description">
<button id="changeContentButton">Change Content</button>
<script>
// Change content on button click
let button = document.getElementById("changeContentButton");
let image = document.getElementById("image");
let heading = document.getElementById("heading");
let description = document.getElementById("description");
// Image paths
const image1 = "/images/image1.png";
const image2 = "/images/image2.png";
// Flag to track current image
let isImage1 = true;
button.addEventListener("click", function () {
heading.innerText = "Content Changed After Button Click!";
description.style.backgroundColor = "lightyellow"; // Change background color
// Toggle image source
if (isImage1) {
image.setAttribute("src", image2);
image.setAttribute("alt", "Second Image Description");
heading.innerText = "Content Changed After Button Click!";
description.style.backgroundColor = "lightyellow"; // Change background color
} else {
image.setAttribute("src", image1);
image.setAttribute("alt", "First Image Description");
heading.innerText = "Original Heading";
description.style.backgroundColor = "white"; // Reset background color
}
// Toggle the flag
isImage1 = !isImage1;
});
</script>
</body>
</html>Key Changes:
Added two image paths (
image1andimage2) for toggling.Introduced a boolean flag
isImage1to track which image is currently displayed.Used an
if-elsestatement to switch the image source andalttext based on the flag.Toggled the flag at the end of the event listener function to ensure the next click switches the image.
Activity Follow-up Questions:
How does the
innerTextproperty differ frominnerHTMLwhen modifying the content of an element?What are some use cases for modifying element attributes, such as
srcorhref?How does the
styleproperty allow you to change the appearance of elements dynamically?
Expected Outcome:
Students will:
Understand how to modify the content, attributes, and styles of HTML elements using JavaScript.
Gain practical experience dynamically changing the appearance and functionality of a webpage by manipulating the DOM.
Explore how DOM manipulation can make web pages interactive and responsive to user actions, such as button clicks.
Last updated