How to display images from an array in JavaScript
In this article, we will explore two methods to display images from an array in JavaScript: using a for loop and the forEach() method.
Method 1: Displaying Images using For Loop #
To begin, let's look at how to display images from an array using a for loop. This method allows us to iterate through the array and create HTML elements dynamically for each image.
<div id="image-container"></div> <script> const imageArray = [ "image1.jpg", "image2.jpg", "image3.jpg" ]; const container = document.getElementById("image-container"); for (let i = 0; i < imageArray.length; i++) { const img = document.createElement("img"); img.src = imageArray[i]; container.appendChild(img); } </script>
Explanation of the above example:
- We define an array of image URLs. Then, we select a <div> element where we want to display the images.
- Using a for loop, we iterate through the array.
- For each image URL, we create an <img> element, set its src attribute to the URL, and append it to the container.
Method 2: display images of array using forEach #
Now, let's explore a more modern and concise approach using the forEach() method. This method simplifies the code for displaying images from an array.
<div id="image-container"></div> <script> const imageArray = [ "image1.jpg", "image2.jpg", "image3.jpg" ]; const container = document.getElementById("image-container"); imageArray.forEach((imageUrl) => { const img = document.createElement("img"); img.src = imageUrl; container.appendChild(img); }); </script>
Explanation:
- We still have our array of image URLs and container element <div>.
- We use the forEach() method on the imageArray to iterate through each URL.
- For each URL, we create an <img> element, set its src attribute, and append it to the container.
Conclusion #
In this article, we explored two methods for displaying images from an array in JavaScript: using a for loop and the forEach() method.
Both approaches achieve the same result, but the forEach() method offers a more concise and modern way to work with arrays.
save
listen
AI Answer
How to display images from an array in JavaScript
0
In this article, we will explore two methods to display images from an array in JavaScrip…
asked
Apu
0 answers
2915
In this article, we will explore two methods to display images from an array in JavaScrip…
Answer Link
answered
Apu