Skip to content Skip to sidebar Skip to footer

Output An Array Of Images In JavaScript

I'm new to JavaScript and I made this code. The purpose of this code is to use JavaScript and HTML to display an ARRAY of images in a website. They all need to be displayed at once

Solution 1:

You have to use array.forEach then append each array item in body.Like this

var ArrayOfImages = ['image1.jpg', 'image2.jpg', 'image3.jpg']; //your assumed array
ArrayOfImages.forEach(function(image) {    // for each link l in ArrayOfImages
  var img = document.createElement('img'); // create an img element
  img.src = image;                         // set its src to the link l
  document.body.appendChild(img);          // append it to the body 
});

See Fiddle: Fiddle

UPDATE

You can also set height and width as your requirement.Like below.

var ArrayOfImages = ['https://upload.wikimedia.org/wikipedia/commons/f/f9/Wiktionary_small.svg', 'https://upload.wikimedia.org/wikipedia/commons/f/f9/Wiktionary_small.svg', 'https://upload.wikimedia.org/wikipedia/commons/f/f9/Wiktionary_small.svg']; //your assumed array
ArrayOfImages.forEach(function(image) {
  var img = document.createElement('img');
  img.src = image;
  img.height = "45";
  img.width = "50";
  document.body.appendChild(img);
});

Post a Comment for "Output An Array Of Images In JavaScript"