Change image source with JavaScript/jQuery
This post will discuss how to change the image source in JavaScript and jQuery.
Changing the image source with JavaScript and jQuery is a common task that many web developers encounter. Whether we want to create a dynamic gallery, a slideshow, a hover effect, or a simple image replacement, we need to know how to manipulate the src attribute of the <img> element.
1. Changing the image source with JavaScript
To change the image source with JavaScript, we can follow these steps:
- Get a reference to the image element by using its id attribute and the
document.getElementById()method. Thedocument.getElementById()method returns a reference to an element by itsidattribute. Theidattribute is a unique identifier for each element on the page. - Assign a new URL to the
srcproperty of the image element, which represents the source URL of the image. Thesrcproperty can be read or written by using the dot notation or the bracket notation.
The complete code for changing the image source with JavaScript looks like this:
JS
|
1 2 3 4 |
document.querySelector("button").onclick = function() { var url = "https://upload.wikimedia.org/wikipedia/commons/5/53/Google_%22G%22_Logo.svg"; document.getElementById("container").src = url; } |
HTML
|
1 2 |
<img id="container" src='https://avatars0.githubusercontent.com/u/70142'/> <button>Refesh</button> |
2. Changing the image source with jQuery
To change the image source with jQuery, we need to follow these steps:
- Create a jQuery object that contains the image element by using its selector and the
$()function. The$()function creates a jQuery object that contains one or more DOM elements using theidselector, a class selector, an element selector, or an HTML string. - Change the
srcattribute of the image element by using the .attr() method and passing a new URL. Theattr()method can set one or more attributes of the selected elements.
The complete code for changing the image source with jQuery looks like this:
JS
|
1 2 3 4 5 6 |
$(document).ready(function() { $("button").click(function() { var url = "https://upload.wikimedia.org/wikipedia/commons/5/53/Google_%22G%22_Logo.svg"; $("#container").attr("src", url); }); }); |
HTML
|
1 2 |
<img id="container" src='https://avatars0.githubusercontent.com/u/70142'/> <button>Refesh</button> |
That’s all about changing the image source in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)