Home > Web Front-end > JS Tutorial > How to dynamically create image elements using JavaScript?

How to dynamically create image elements using JavaScript?

王林
Release: 2023-08-24 18:21:14
forward
1252 people have browsed it

How to dynamically create image elements using JavaScript?

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

In some cases, we need to dynamically add pictures to the web page. For example, we store an unknown amount of movie data in a database. We need to get movie data and we need to display movie images along with details of each movie. In this case, we need to use JavaScript to append the image and data to the DOM.

Next, we will learn to use JavaScript to add image elements to web pages.

Use Document.createElement() method

The document.createElement() method creates any HTML element using JavaScript. It takes the tag name as parameter and returns the HTML element.

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

grammar

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

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

In the above syntax, we create an image element using the createElement() method and update the "src" attribute of the image element.

Example

In the example below, we first create the image element. After that, we update its “src” attribute with the URL of the image we want to display on the web page.

Next, we access the predefined div element from the DOM using its id and append the newly created image as a child of the div element using the appendChild() method.

In the output, the user can observe that the 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>
Copy after login

Example

In the example below, we create buttons. Whenever the user clicks the button, it executes the createImage() function.

In the createImage() function, we use the createElement() method to create a new image element and update its "src" attribute value. Additionally, we use the setAttribute() method to set the id, height, and width of the image.

In the output, the user can click a button to view the image in 200 x 200 dimensions. However, the user 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>
Copy after login

Use Image() constructor

image() is a constructor used to create an instance of an image element in JavaScript. We create an instance of the image in JavaScript using the constructor with the "new" keyword and attach it to the DOM object.

grammar

Users can create images through JavaScript using the Image() constructor according to the following syntax.

Let img = new Image();
img.src = URL;
Copy after login

In the above syntax, we create an instance of the image element using the image() constructor and update the value of its src attribute.

Example

In the example below, when the user clicks the button, it executes the createImage() function to dynamically attach to the DOM.

In the createImage() function, we use the Image() constructor to initialize the image instance and then update the value of its src attribute. Additionally, we set the width and height of the image by updating the attribute values ​​and attaching it 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>
Copy after login

Example

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

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

In the output, the user can click the button to see five dynamic images on the web page. Additionally, the image changes every time the user clicks the button.

<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>
Copy after login

We learned two ways to dynamically attach images to Dom elements. The createElement() method creates an instance of any HTML element, including image elements. The image() constructor is used only to create instances of image elements, not other HTML elements.

In addition, as in the previous example, we may get an array of image URLs during real-time development and need to add multiple dynamic images to the web page.

The above is the detailed content of How to dynamically create image elements using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template