Skip to content

Instantly share code, notes, and snippets.

@monners
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save monners/87101747f81b9b299f27 to your computer and use it in GitHub Desktop.
Save monners/87101747f81b9b299f27 to your computer and use it in GitHub Desktop.

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>

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment