Change the src of an HTML img tag in jQuery

We all know that we can show an image on a web page using the HTML <img> tag just like you can see below:

<img src="path/image1.jpg" alt="image">

Now I will show you how to change the image in JavaScript. Here we will actually change the src of our HTML img tag in jQuery.

First of all, let’s see our HTML code below:

<img class="img" src="path/image1.jpg" alt="image">

<button id="change-img">Change image</button>

In our HTML code, we have an img tag and a button. Both of these has an ID which we are going to use in our jQuery JavaScript code soon.

Now we want that, when we click the button, it will change the src of our HTML image tag and we will be able to show a different image on the web page.

Now below is the jQuery code to change the img src file when we click the button:

$( "#change-img" ).click(function() {
        $(".img").attr("src","path/image2.jpg");
});

In our jQuery code, we have applied the click method to the button. When the button click event occurs, it will apply the attr() method and change the src value of our <img> tag. The jQuery attr() method can change any attribute value. Here we are using it to change the value of src.




Also, read:

That’s it. Now we can run our code to see if we can change the image on clicking the button. If everything goes right, we can see the=at the image on our web page changes when we click the button. That means we have successfully able to change the src of our HTML img tag in jQuery.


Leave a Reply

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