Home > database >  How to display images from a loop JavaScript
How to display images from a loop JavaScript

Time:02-15

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

CodePudding user response:

Try appendChild:

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

CodePudding user response:

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

CodePudding user response:

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;
   
}
  • Related