Change the “src” attribute of an image using JavaScript.

This is a tutorial on how to change the “src” attribute of an image using JavaScript.

The src attribute specifies the URL of an image. Therefore, by setting a new src, we can dynamically change the image in question.

In this post, I will show you how to accomplish this using both regular JavaScript and jQuery.

Changing the src attribute using regular JavaScript.

If you’re not already using jQuery, then there is no sense in including the library just to manipulate the src attribute. Instead, you can just use vanilla JavaScript, which tends to be faster.

Take a look at the example below:

<img id="myImage" src="https://thisinterestsme.com/LOGO.png">

<script>
    //Modify the src attribute of the image with the ID "myImage"
    document.getElementById("myImage").src = 'img/new-image.jpg';
</script>

If you run the snippet above, you will see that the src attribute of our image element is replaced by our JavaScript code.

A more verbose example for those of you who want to understand what is going on here:

//Get our img element by using document.getElementById
var img = document.getElementById("myImage");

//Set the src property of our element to the new image URL
img.src = 'img/new-image.jpg';

In this case, we have broken the process up into two steps:

  1. We retrieved the img element from our HTML DOM by using the method document.getElementById(). We passed “myImage” in as the parameter because that is the ID of our image.
  2. After retrieving the img, we were able to modify its src attribute and assign a new URL.

This will force the browser to load our new image.

Changing the img src using jQuery.

If you’re already using the jQuery library and you would like to keep your code consistent, you can use the following method:

//Change the img property using jQuery's attr method
$("#myImage").attr("src", 'img/new-image.jpg');

In the code above, we referenced the image by its ID and then used jQuery’s attr() method to set a new value for its src attribute.

Determining when the new image is loaded.

If you need to do something after the new image has loaded, then you can attach jQuery’s load() method to our example above:

//Change the img property and use load() to figure out when
//the new image has been loaded
$("#myImage").attr("src", 'img/new-image.jpg').load(function(){
    alert('New image loaded!');
});

Once jQuery has changed the src property and the image from the new URL has been loaded in the browser, the code inside the load() method will execute. However, this load block will not execute if the image in question doesn’t exist.