To change the image src using jQuery, the simplest way is to use the jQuery attr() method:
$("#img-1").attr("src","anotherImg.jpg");
Let’s say I have the following HTML code:
To change the image src of #img-1 from img.jpg to anotherImg.jpg, we will use the jQuery attr() method like in the following Javascript code:
$("#img-1").attr("src","anotherImg.jpg");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#img-1").attr("src","anotherImg.jpg");
Changing Image Src Using jQuery with a Click
Many times when creating a web page and the user experience, we want to change an image after an interaction with another element on the web page.
To change the image src using jQuery, we can combine the attr() method with a click event.
Let’s say we have the same HTML from above.
We have two images, tpe-main.png is a picture of gears in png form, and tpe-main.jpg is the same image, but in jpg form.
If we want to change the image from the .jpg version to the .png version when we click the #click-me div, we can add the following Javascript code to accomplish this:
$("#click-me").click(function(){
$("#img-1").attr("src","/wp-content/uploads/2021/11/tpe-main.png");
});
The final code and output for this example of how to change the source of an image using the jQuery attr() method and Javascript is below:
Code Output:
Full Code:
<script>
$("#click-me").click(function(){
$("#img-1").attr("src","/wp-content/uploads/2021/11/tpe-main.png");
});
</script>
Hopefully this article has helped you understand how you can update the image source (src) using jQuery.