Table of Contents
Use Document.createElement() method
grammar
Example
Using the document.createElement() method to Create image element dynamically using JavaScript
Use Image() constructor
Using the Image() constructor to Create image element dynamically using JavaScript
Home Web Front-end JS Tutorial How to dynamically create image elements using JavaScript?

How to dynamically create image elements using JavaScript?

Aug 24, 2023 pm 06:21 PM

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 id="Using-the-i-document-createElement-method-i-to-Create-image-element-dynamically-using-JavaScript">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 id="Using-the-i-document-createElement-method-i-to-Create-image-element-dynamically-using-JavaScript">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 id="Using-the-i-Image-constructor-i-to-Create-image-element-dynamically-using-JavaScript">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 id="Using-the-i-Image-constructor-i-to-Create-image-element-dynamically-using-JavaScript">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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

jQuery Check if Date is Valid jQuery Check if Date is Valid Mar 01, 2025 am 08:51 AM

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

jQuery get element padding/margin jQuery get element padding/margin Mar 01, 2025 am 08:53 AM

This article discusses how to use jQuery to obtain and set the inner margin and margin values ​​of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values ​​can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

10 jQuery Accordions Tabs 10 jQuery Accordions Tabs Mar 01, 2025 am 01:34 AM

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

10 Worth Checking Out jQuery Plugins 10 Worth Checking Out jQuery Plugins Mar 01, 2025 am 01:29 AM

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

HTTP Debugging with Node and http-console HTTP Debugging with Node and http-console Mar 01, 2025 am 01:37 AM

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

jquery add scrollbar to div jquery add scrollbar to div Mar 01, 2025 am 01:30 AM

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

See all articles