Dynamically set image src using JavaScript | Simple HTML Example code

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>
<html>
<body>

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

   <script>
        document.getElementById('image').src = 'bg.jpg';
    </script> 
</body>
</html>

Output:

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.