How to add a list of images to the document from an array of URLs?

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]; // img[i] refers to the current URL.
    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 the global i and j variables
  • 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(url, index, originalArray) {
    var img = document.createElement('img');
    img.src = url;
    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

Leave a Comment