Open In App

How to create an image element dynamically using JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given an HTML element, the task is to create an <img> element and append it to the document using JavaScript. In the following examples, when someone clicks on the button the <img> element is created.

These are the following ways to create an image element dynamically:

Approach 1: Using createElement() method

  • Create an empty img element using document.createElement() method.
  • Then set its attributes like (src, height, width, alt, title, etc).
  • Finally, insert it into the document.

Example: This example implements the above approach. 

html




<!DOCTYPE HTML>
<html>
 
<head>
    <title>
        How to create an image element
        dynamically using JavaScript ?
    </title>
</head>
 
<body id="body" style="text-align:center;">
 
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <h3>
        Click on the button to add image element
    </h3>
 
    <button onclick="GFG_Fun()">
        click here
    </button>
 
    <h2 id="result" style="color:green;"></h2>
 
    <script>
        let res = document.getElementById('result');
 
        function GFG_Fun() {
            let img = document.createElement('img');
            img.src =
            document.getElementById('body').appendChild(img);
            res.innerHTML = "Image Element Added.";
        }
    </script>
</body>
 
</html>


Output:

Approach 2: Using image() constructor

  • Create an empty image instance using new Image().
  • Then set its attributes like (src, height, width, alt, title, etc).
  • Finally, insert it into the document.

Example: This example implements the above approach. 

html




<!DOCTYPE HTML>
<html>
 
<head>
    <title>
        How to create an image element
        dynamically using JavaScript ?
    </title>
</head>
 
<body id="body" style="text-align:center;">
 
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <h3>
        Click on the button to add image element
    </h3>
 
    <button onclick="GFG_Fun()">
        click here
    </button>
 
    <h2 id="result" style="color:green;"></h2>
 
    <script>
        let res = document.getElementById('result');
 
        function GFG_Fun() {
            let img = new Image();
            img.src =
            document.getElementById('body').appendChild(img);
            res.innerHTML = "Image Element Added.";
        }
    </script>
</body>
 
</html>


Output:

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Last Updated : 29 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads