22 Votes

jQuery: Change Image

Question by Guest | 2015-05-30 at 16:10

I am showing a normal image in my HTML code and I would like to replace this image with another one dynamically using JavaScript (jQuery).

The HTML for the images is looking for example like that.

<img id="img1" src="test.jpg">

Now, I would like to change "test.jpg" to "new.jpg", for instance. In other words, I would like to modify the attribute SRC of the IMG tag. Is this possible using jQuery?

ReplyPositiveNegative
2Best Answer2 Votes

Using jQuery, you can simply exchange your image with .attr(). In the following example, I will take the values from your question.

$("#img1").attr("src", "new.jpg");

First of all, we are using the selector $("#img1") in order to select the image with the ID "img1". After that, we are using .attr() in order to give the attribute "src" the new value "new.jpg". With this, you have changed your image.
2015-05-30 at 16:44

ReplyPositive Negative
Reply

Related Topics

Android Splash Screen Tutorial

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.