Home >Web Front-end >CSS Tutorial >How to Change an Image on Click Using Simple JavaScript Methods?
How to Change Image on Click Using Simple Methods
In this scenario, you want to replace an image with another version of it when clicking on the parent element. While you could use intricate JavaScript frameworks like jQuery, this task can be achieved with simpler methods.
Consider the following HTML structure:
<li><img src="default.jpg" alt="Image 1" /></li> <li><img src="default.jpg" alt="Image 2" /></li> <li><img src="default.jpg" alt="Image 3" /></li> <li><img src="default.jpg" alt="Image 4" /></li> <li><img src="default.jpg" alt="Image 5" /></li>
Using an ID Attribute:
Assign a unique ID to the image you want to change:
<img src="default.jpg" alt="Image 1">
Then, in your JavaScript, use the document.getElementById function:
document.getElementById("image1").src = "colored.jpg";
Using a Class Selector:
Add a class to the image you want to change:
<img src="default.jpg" alt="Image 1" class="image" />
Document.querySelectorAll returns all elements that match a given CSS selector.
const images = document.querySelectorAll(".image"); images.forEach((image) => { image.src = "colored.jpg"; });
Using the Active Pseudo-Class:
When an element is clicked, the active pseudo-class is applied to it. This can be utilized to change the image when an element is clicked:
<img src="default.jpg" alt="Image 1" />
li:active img { src: "colored.jpg"; }
These methods provide simpler alternatives for updating images on click, without relying on complex JavaScript frameworks.
The above is the detailed content of How to Change an Image on Click Using Simple JavaScript Methods?. For more information, please follow other related articles on the PHP Chinese website!