How to Change Image Source with Pure JavaScript or jQuery
In this tutorial, we will learn how to set a new value for the src
attribute on an img
element in HTML using pure JavaScript and jQuery.
With JavaScript
To change the image src
attribute image we will first need to get the element from the DOM document then set a new value on its src
property.
<img src="cat.jpg" alt="animal" id="picture">
var pic = document.getElementById('picture');
pic.src = 'dog.jpg'
In the above example, we are getting the img
element by its ID and storing it in a variable. Then we are setting a new src
property value with the assignment operator (=
).
Alternatively, we can condense the above into a one-liner if there is no need to use the element again:
document.getElementById('picture').src = 'dog.jpg';
Change Image Source With jQuery
The method will be the same in jQuery as in pure JavaScript but with a different markup.
<img src="cat.jpg" alt="animal" id="picture">
$('#picture').attr('src', 'dog.jpg');
Conclusion
You now know how to change the source attribute of any HTML element using vanilla JavaScript and jQuery.