Skip to content

Change image src using JavaScript | Program onClick event Example

  • by

How can I change the src attribute of an img tag using javascript?

Give your img tag an id, then access it use getElementById to assign a new image in img change, it will Change image src using.

Simple one-line code for it:

document.getElementById("imageid").src="../newimg/abc.jpg";

Example code change image src using JavaScript

HTML example code to change the src of an img tag Programmatically in JavaScript (JS).

We created a function to change the image dynamically on the click button (using the onClick event).

 <!DOCTYPE html>
<html>
<body>

   <img id="imageid" src="abc.png" id="image" />

   <button onclick="changSRC()">Change Image</button>

   <script>
    function changSRC() {
        document.getElementById("imageid").src="xyz.png";
        alert("changed")
    }
    </script> 
</body>
</html>

Output:

Change image src using JavaScript

Q: How to JavaScript set image src dynamically?

Answer: Use id into img tag and getElementById…Read more

Do comment if you know a better example or have suggestions or doubts on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *