doug22
doug22

Reputation: 77

How to display images from a loop JavaScript

I have an array of images and would like to display them in a div tag using a loop, but none of the images are showing.

const images = ["images/image1", "images/image2", "images/image3"];


            
for (let x = 0; x < images.length; x++) {
                    
    const element = '<img src="' + images[0] + '">'
    let pic = document.querySelector('.images').innerHTML += element;
    pic;
}

Upvotes: 1

Views: 7526

Answers (3)

QuinnF
QuinnF

Reputation: 2149

Try appendChild:

const images = ["images/image1", "images/image2", "images/image3"];
const container = document.querySelector('#images');
for (let image of images) {
  const htmlImage = document.createElement("img");
  htmlImage.src = image;
  container.appendChild(htmlImage);
}

Upvotes: 0

epascarello
epascarello

Reputation: 207501

You are only ever referencing the first index of the array since you used images[0]. You should be using the index.

const images = ["http://placekitten.com/200/300", "http://placekitten.com/100/300", "http://placekitten.com/400/300"];

for (let x = 0; x < images.length; x++) {            
    const element = '<img src="' + images[x] + '">'
    document.querySelector('.images').innerHTML += element;
}
<div class="images"></div>

You you want to use innerHTML to add the images, using map() and join() would be a better solution since you only will update the DOM once.

const images = ["http://placekitten.com/200/300", "http://placekitten.com/100/300", "http://placekitten.com/400/300"];


const myHtml = images.map(function(path) {
  return '<img src="' + path + '">';
}).join('');

document.querySelector('.images').innerHTML = myHtml;
<div class="images"></div>

Other option is creating the elements and appending them.

const images = ["http://placekitten.com/200/300", "http://placekitten.com/100/300", "http://placekitten.com/400/300"];

const outElem = document.querySelector('.images');

images.forEach(function (path) {
  const img = document.createElement("img");
  img.src = path;
  outElem.appendChild(img);
});
<div class="images"></div>

Upvotes: 1

hous
hous

Reputation: 116

try this:

const images = ["images/image1", "images/image2", "images/image3"];


            
for (let x = 0; x < images.length; x++) {
                    
    const element = '<img src="' + images[x] + '">'
    document.querySelector('.images').innerHTML += element;
   
}

Upvotes: 0

Related Questions