To change the src of an image using JavaScript, we simply use the image src property along with the getElementById method.

document.getElementById("img1").src = "anotherImg.jpg";

Let’s say I have the following HTML code:


To change the image src of #img1 from img.jpg to anotherImg.jpg, we will use the src property in the following JavaScript code:

document.getElementById("img1").src = "anotherImg.jpg";

Using JavaScript to Change the Image src with a Click

To change the source of an image we can combine the src property with a click event.

Let’s say we have the same HTML from above.

Change image

We have two images, example-img1.png is a picture of gears and example-img2.png is the same image, but with different colors.

We have added an onclick event to the #click-me div which will run a function where we can change the image from the example-img1.png version to the example-img2.png version.

Here is the function below that will accomplish this:

function changeIMG(){
  document.getElementById("img-1").src = "https://daztech.com/wp-content/uploads/example-img2.png";
};

The final code and output for this example of how to change the source of an image using the src property and JavaScript is below:

Code Output:

Change image

Full Code:

Change image



Using JavaScript to Toggle Image src with a Click

To toggle the source of an image we simply need access to another image, or use our original image URL.

We will use the same HTML.

Toggle image

We have two images, example-img1.png is a picture of gears and example-img2.png is the same image, but with different colors. We will toggle between these two images.

We will modify our function slightly to toggle the image instead of just changing it once.

Here is the function below that will accomplish this:

function toggleIMG(){
  if( document.getElementById("img-2").src == "https://daztech.com/wp-content/uploads/2024/02/example-img1-1.png" ) {
 document.getElementById("img-2").src = "https://daztech.com/wp-content/uploads/example-img2.png"; 
  } else {
 document.getElementById("img-2").src = "https://daztech.com/wp-content/uploads/2024/02/example-img1-1.png";  
  }
};

The final code and output for this example of how to toggle the source of an image using the src property and JavaScript is below:

Code Output:

Toggle image

Full Code:

Toggle image



Hopefully this article has helped you understand how to use JavaScript to change the image src of an image.

Categorized in:

JavaScript,

Last Update: April 2, 2024