monners
4/7/2015 - 9:06 AM

Question.md

One way to do this is to loop over your array of images, create an img element for each, set the element's src to the current image source in your array, then append it to your container. This would look like:

var imgs = ['http://lorempizza.com/380/240', 'http://dummyimage.com/250/ffffff/000000', 'http://lorempixel.com/g/400/200/', 'http://lorempixel.com/g/400/200/sports/'];
var container = document.getElementById('imageContainer');

for (var i = 0, j = imgs.length; i < j; i++) {
    var img = document.createElement('img');
    img.src = imgs[i];
    container.appendChild(img);
}

However, this isn't particularly efficient:

  • We're using an unnecessary loop
  • We're querying the dom on every iteration
  • We're introducing a global i variable
  • We're not using JavaScript's wonderful Array methods!

Instead, let's use a documentFragment and JavaScript's forEach Array method.

var imgs = ['http://lorempizza.com/380/240', 'http://dummyimage.com/250/ffffff/000000', 'http://lorempixel.com/g/400/200/', 'http://lorempixel.com/g/400/200/sports/'];
var container = document.getElementById('imageContainer');
var docFrag = document.createDocumentFragment();


imgs.forEach(function(cur, index, arr) {
    var img = document.createElement('img');
    img.src = cur;
    docFrag.appendChild(img);
});


container.appendChild(docFrag);

This way we're:

  • Only hitting the DOM once
  • Not introducing global variables
  • Maintaining cleaner, easier to read code!

Then just to make sure your new images look nice, add a bit of CSS to the mix:

#imageContainer img {
    width: 20%;
    height: auto;
}

Bam! Here's a fiddle

How do you add a list of image links to a document?

Suppose I have an array full of image source URLs, like:

var imgs = ['http://lorempizza.com/380/240', 'http://dummyimage.com/250/ffffff/000000', 'http://lorempixel.com/g/400/200/', 'http://lorempixel.com/g/400/200/sports/'];

How do I grab all of those images and insert them into my page at a particular location? Say...

<div id="imageContainer"></div>