Change image src using onClick event in JavaScript

In this short post, we will learn how to change/replace the value of the src (source) attribute of an image in JavaScript.

To change image src using onClick() event, first we have to get the element using getElementById() and then change the source on click of the button.

Let’s understand it using an example.

Change image src using JavaScript

Suppose we have an image on our web page and we want to change the src (source) path when a user clicks the “Change Image” button.

<img id="myImg" src="1.jpg"/>
<button onclick="changeImage()">Change Image</button>

Here, we have an <img> tag with an id = “myImg“. And we have also added an onClick() event to the button that will trigger the changeImage() function when clicked by a user.

In the script section, we have created the function changeImage() to change the image dynamically on click on the button using the onClick event.

<script>
  const image = document.getElementById("myImg");
  function changeImage() {
   image.src = "2.jpg";
  }
</script>        

Here, when the function changeImage() gets triggered, it gets the < img > element in the DOM using the getElementById() method and the change the source (src) of the old image with the new one.

Change Multiple image src onClick Event

To change multiple image src using onclick event:

  1. Add a class name to each img element,
  2. Target all images in DOM using querySelectorAll() method
  3. Loop through each element and change/replace the img source (src)

Let’s see an example:

Here we have three images on our HTML page.

 <img class="myImg" src="1.jpg" width="75%" alt="" srcset="" />
 <img class="myImg" src="1.jpg" width="75%" alt="" srcset="" />
 <img class="myImg" src="1.jpg" width="75%" alt="" srcset="" />
 <button onclick="changeAllImage()">Change Image</button>

Here, we have three images with class name “myImg” and a button with onclick() event to trigger the changeAllImage() function.

In the script section, we have coded the JavaScript function.

<script>
   function changeAllImage() {
      const image = document.querySelectorAll(".myImg");
      image.forEach(element => {
         element.src = '2.jpg'
     }); 
   }
</script>

When the changeAllImage() function is triggered, it gets a NodeList of all the <img> tags with class name “myImg” using querySelectorAll() method.

Next, we loop through all the images using forEach() method and change/replace the source (src) of the images with a new one.


Related Topics:

How to change image source using CSS

How to change image on hover using JavaScript

JavaScript: Change Background Color of a Webpage

Change Text Color Using JavaScript with Example

How to get the id of a button clicked in JavaScript

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top