To get the source of an image, we can use jQuery to get the img src using the attr() method.
$('#img1').attr('src');
The jQuery attr method will return the location of the file as a string.
Say we have the following html:
If we used the jQuery attr() method on the image, $('#img1').attr('src');
, we would get the following returned:
https://daztech.com/wp-content/uploads/2024/02/example-img1-1.png
An example using the attr() method to get and set the img src
Below is an example of how we can use jQuery to get the src of an image using the attr() method and how we can later set the src of that image.
Click Me to Replace the image above.
Let’s say we have another image called “example-img2” which is in the same location as the image above. When we click the button, we want to swap out that image. We will use the jQuery attr() method to get the src of the image and store it as a variable. We will use the JavaScript indexOf() method to get the location of “example-img1” and use the substring() method to get the first part of the image location. Then we will add the new image file name and replace the old image. Here is the JavaScript code below:
$("#click-me").click(function(){
var oldImgAddress = $('#img1').attr('src');
var indexOfImage = oldImgAddress.indexOf('example-img1.png');
var firstPartOfString = oldImgAddress.substring(0,indexOfImage);
var newImgAddress = firstPartOfString + "example-img2.png";
$('#img1').attr('src',newImgAddress);
});
The final code and output for this example is below:
Code Output:
Full Code:
Click Me to Replace the image above.
Hopefully this article has been useful in helping you understand the jQuery attr() method for getting an img src.