How to Add Dynamic Images in HTML Using Javascript

You can add dynamic images as well as static images to HTML. If you want to insert a dynamic image in the HTML document to show that image on a web page, you have to follow the steps which are given below. Using these steps, you can easily add or insert an image in the document. Dynamic images enable different image files to be displayed.

In this tutorial, we would be having an HTML element and our task would be to create an image (<img>) element and add it to the HTML document with the help of JavaScript. In this example when a user clicks on the button then the <img> element is created. You can also replace click events with any other JavaScript event.


JavaScript allows you to execute complex features on web pages and to add an image to an HTML document. JavaScript is involved every time a web page displays any static information for you to view or displaying timely content updates, animated 2D/3D graphics, interactive maps, scrolling video jukeboxes, etc. JavaScript is the third major web technologies, after the HTML and CSS.

Steps for Adding Dynamic Images in HTML using JavaScript

Adding a dynamic image in HTML with the use of JavaScript requires a few steps, particularly if you want to change some attributes and details. Here’s a complete step-by-step method that covers all that you’ll need with the help of an example.

Step 1: You need to create an empty img element by using this method, document.createElement().

Step 2: In the next step, you need to set its different attributes like (height, width, src, alt, title, etc).

Step 3: Now lastly under the final step, you need to insert this into the HTML document.

Below is the example that implements the above-mentioned approach.





      Creating an image element 

        dynamically using JavaScript



 <body id = "body" style = "text-align:center;">   

    <h1 style = "color:blue;" > 



    <p id = "GFG_UP" style = 

            "font-size: 15px; font-weight: bold;"> 


    <button onclick = "GFG_Fun()"> 

        click here 


    <p id = "GFG_DOWN" style = 

            "color:blue; font-size: 20px; font-weight: bold;"> 



        var up = document.getElementById('GFG_UP'); 

        up.innerHTML = "Click on the button to add image element"; 

        var down = document.getElementById('GFG_DOWN');           

        function GFG_Fun() { 

            var img = document.createElement('img'); 

            img.src = 



            down.innerHTML = "Image Element Added."; 






This brings us to the end of this article. Finally, you learned how to add a dynamic image to HTML with the use of JavaScript. With the help of the above-defined method, you can add any number of images dynamically in the HTML. We believe you were able to learn something new and exciting. If you are looking for a web development company in New York, Contact us.