How to create an image element dynamically using JavaScript ?

Given an HTML element and 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 then the <img> element is created. We can replace the click event with any other JavaScript event.Â
Approach 1:
- 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;">        zambiatek    </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:
- 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;">        zambiatek    </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.




