How to useArray.map() Method in Javascript
We can use the map() method of the array to create an array of <img> tags and then join them into a string to display them in the HTML.
Example: In this example, we create an array of <img> tags using the map() method of the array. We set the src attribute of each <img> tag to the corresponding image URL using a template literal. Finally, we join the array of <img> tags into a string and set it as the innerHTML of the container element.
<!DOCTYPE html>
<html>
<head>
<title>Display Images from Array</title>
</head>
<body>
<h1 style="color: green;">
w3wiki
</h1>
<h1>
Display Images from Array
using Array.map()
</h1>
<div id="image-container"></div>
<script>
const images = [
'https://media.w3wiki.org/wp-content/uploads/20230306120634/unnamed.jpg',
'https://media.w3wiki.org/wp-content/uploads/20230306120634/unnamed.jpg',
'https://media.w3wiki.org/wp-content/uploads/20230306120634/unnamed.jpg'
];
const container =
document.getElementById('image-container');
const imageTags =
images.map(img => `<img src="${img}">`);
container.innerHTML = imageTags.join('');
</script>
</body>
</html>
Output:
How to display images from an array in JavaScript ?
Displaying images from an array in JavaScript involves storing image URLs within the array and dynamically generating HTML elements, such as <img>, using JavaScript. By iterating over the array, each image URL is used to create <img> elements, which are then appended to the document for display.
Below are the approaches that could be used to display images from an array in JavaScript
Table of Content
- Using a For Loop
- Using Array.map() Method
- Using a forEach() method
Syntax:
<img src="image-url" alt="alternative-text">
Here, the src attribute specifies the URL of the image, and the alt attribute provides alternative text for the image if it cannot be displayed.