Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #Array #forEach

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:

  1. We define an array of image URLs. Then, we select a <div> element where we want to display the images.
  2. Using a for loop, we iterate through the array.
  3. 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:

  1. We still have our array of image URLs and container element <div>.
  2. We use the forEach() method on the imageArray to iterate through each URL.
  3. 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
Write Your Answer
loading
back
View All