Skip to content

Dynamically set image src using JavaScript | Simple HTML Example code

  • by

Use id into img tag and getElementById method then assign imager source to set image src in JavaScript.

document.getElementById('image').src = 'http://yourImagePathHere';

Also, one way to solve this is to use document.createElement and create your html img and set it.

Example of JavaScript set image src dynamically

Let’s see HTML example code, Give your img tag an id and use getElementById to assign an image in script code.

Note: Use script code after img tag, otherwise, an error occurs.

<!DOCTYPE html>

   <img src="" id="image" />

        document.getElementById('image').src = 'bg.jpg';


Dynamically set image src using JavaScript

Do comment if you have a better example or have any doubts/suggestions 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 *