Open In App

How to create an image element dynamically using JavaScript ?

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

Example: This example implements the above approach. 






<!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

Example: This example implements the above approach. 




<!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.


Article Tags :