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;
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>
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>
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;
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>
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>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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

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-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

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

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
