How to create an image element dynamically using JavaScript

We can create image element and append it to a document using JavaScript so that when someone clicks on the button the image will be created.

We can get this by

Approach:

  • 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.
<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>
      
    <p id = "GFG_UP" style =
            "font-size: 15px; font-weight: bold;">
    </p>
      
    <button onclick = "GFG_Fun()">
        click here
    </button>
      
    <p id = "GFG_DOWN" style =
            "color:green; font-size: 20px; font-weight: bold;">
    </p>
      
    <script>
        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 = new Image();
            img.src =
'Image source';
            document.getElementById('body').appendChild(img);
            down.innerHTML = "Image Element Added.";
        }
    </script>
</body>
</html>

Leave a comment

Your email address will not be published. Required fields are marked *