How to create an image element dynamically using JavaScript?


In HTML, the image element is used to show the images on the web page. It takes multiple attributes according to the requirements, such as ‘src’, ‘alttext’, ‘height’, ‘width’, etc.

In some situations, we require to dynamically add images to the web page. For example, we have stored an unknown number of movie data in the database. We need to fetch the movie data, and we need to show the movie image with details for each movie. In this case, we need to append the image and data to the DOM using JavaScript.

Below, we will learn to add image elements to the web page using JavaScript.

Using the Document.createElement() Method

The document.createElement() method uses JavaScript to create any HTML element. It takes the tag name as a parameter and returns the HTML element.

After creating the HTML element in JavaScript, we can modify its various attributes and append it to the DOM to show the image on the web page.

Syntax

Users can follow the syntax below to use the document.createElement() method to create image elements dynamically.

let dynamicImage = document.createElement('img');
dynamicImage.src = URL;

In the above syntax, we have created the image element using the createElement() method and updated the ‘src’ attribute of the image element.

Example

In the example below, we have created the image element first. After that, we updated its ‘src’ attribute with the image URL we wanted to show on the web page.

Next, we accessed the pre-defined div element from the DOM using its id and used the appendChild() method to append the newly created image as a child of the div element.

In the output, users can observe that an image is added using JavaScript.

<html>
<body>
   <h3>Using the <i> document.createElement() method </i> to Create image element dynamically using JavaScript </h3>
   <div id = "img"> </div>
   <script>
      let img = document.getElementById('img');
      // Create image element
      let dynamicImage = document.createElement('img');
      // Initialize the image source
      dynamicImage.src = "https://www.tutorialspoint.com/static/images/logo.png";
      // Add image to DOM
      img.appendChild(dynamicImage);
   </script>
</body>
</html>

Example

In the example below, we created the button. Whenever users click the button, it executes the createImage() function.

In the createImage() function, we create a new image element using the createElement() method and update its ‘src’ attribute value. Furthermore, we use the setAttribute() method to set the image's id, height, and width.

In the output, users can click on the button to see the image of 200 x 200 dimensions. However, users can change the dimensions in the code and run the code to observe the output.

<html>
<body>
   <h3>Using the <i> document.createElement() method </i> to Create image element dynamically using JavaScript </h3>
   <div id = "img"> </div>
   <button id = "addImage" onclick = "createImage()"> Create Image </button>
   <script>
      function createImage() {
         let img = document.getElementById('img');
         let newImage = document.createElement('img');
         newImage.src = "https://www.tutorialspoint.com/static/images/simply-easy-learning.png";
         // Set attribute values for the image
         newImage.setAttribute('id', 'myImage');
         newImage.setAttribute('width', '200px');
         newImage.setAttribute('height', '200px');
         img.appendChild(newImage);
      }
   
   </script>
</body>
</html>

Using the Image() Constructor

The image() is a constructor function used to create an instance of an image element in JavaScript. We use the constructor function with a ‘new’ keyword to create an instance of the image in JavaScript and append it to the DOM object.

Syntax

Users can follow the syntax below to use the Image() constructor to create an image using JavaScript.

Let img = new Image();
img.src = URL;

In the above syntax, we created the instance of an image element using the image() constructor function and updated its src attribute’s value.

Example

In the example below, when users click the button, it executes the createImage() function to append dynamically to the DOM.

In the createImage() function, we initialize the image instance using the Image() constructor function and update its src attribute’s value after that. Also, we set the width and height for the image by updating attribute values and append as a child of the div element.

<html>
<body>
   <h3>Using the <i> Image() constructor </i> to Create image element dynamically using JavaScript</h3>
   <div id = "img"> </div>
   <button id = "addImage" onclick = "createImage()"> Create Image </button>
   <script>
      function createImage() {
         let img = document.getElementById('img');
         let devImage = new Image();
         devImage.src = "https://www.tutorialspoint.com/static/images/development.svg";
         devImage.setAttribute('width', '300px');
         devImage.setAttribute('height', '300px');
         img.appendChild(devImage);
      }
   </script>
</body>
</html>

Example

In the example below, we use JavaScript to append multiple images to the web page.

In the addMultiple() function, we have an array of image urls. We traverse the array, and in each iteration, we create a new image element, update the src attribute with the given source URL, and append it to the DOM.

In the output, users can click the button to see five dynamic images on the web page. Also, every time users click the button, it changes the image.

<html>
<body>
   <h3>Using the <i> Image() constructor </i> to Create image element dynamically using JavaScript</h3>
   <div id = "img"> </div>
   <br> <br>
   <button id = "addImage" onclick = "AddMultiple()"> Add Multiple Images </button>
   <script>
      function AddMultiple() {
         let img = document.getElementById('img');
         let imageURLS = [
            "https://picsum.photos/200/300",
            "https://picsum.photos/200/300/?blur",
            "https://picsum.photos/200/300.webp",
            "https://picsum.photos/200",
            "https://picsum.photos/200/300"
         ]
         // Fetch random images and append to the DOM
         for (let i = 0; i < 5; i++) {
            let randomImage = new Image();
            randomImage.src = imageURLS[i];
            randomImage.alt = "Random Image";
            randomImage.width = 100;
            randomImage.height = 100;
            // Add right and left margin to the image
            randomImage.style.marginRight = "10px";
            randomImage.style.marginLeft = "10px";
            img.appendChild(randomImage);
         }
      }
   </script>
</body>
</html>

We learned two ways to append the image dynamically to the Dom element. The createElement() method creates an instance of any HTML element, including the image element. The image() constructor function is used only for creating the instance of the image element, not other HTML elements.

Furthermore, as in the last example, we may get an array of image URLs in real-time development, and we need to append multiple dynamic images to the web page.

Updated on: 14-Jul-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements