How to Change an Image on Click Using Simple JavaScript Methods?

Mary-Kate Olsen
Release: 2024-11-17 14:57:02
Original
181 people have browsed it

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>
Copy after login

Using an ID Attribute:

Assign a unique ID to the image you want to change:

<img src="default.jpg" alt="Image 1">
Copy after login

Then, in your JavaScript, use the document.getElementById function:

document.getElementById("image1").src = "colored.jpg";
Copy after login

Using a Class Selector:

Add a class to the image you want to change:

<img src="default.jpg" alt="Image 1" class="image" />
Copy after login

Document.querySelectorAll returns all elements that match a given CSS selector.

const images = document.querySelectorAll(".image");
images.forEach((image) => {
  image.src = "colored.jpg";
});
Copy after login

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" />
Copy after login
li:active img {
  src: "colored.jpg";
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template