Skip to content

Instantly share code, notes, and snippets.

@MadaraUchiha
Forked from monners/Question.md
Last active August 29, 2015 14:18
Show Gist options
  • Save MadaraUchiha/4bba0a1bc1f4d6c1bdd6 to your computer and use it in GitHub Desktop.
Save MadaraUchiha/4bba0a1bc1f4d6c1bdd6 to your computer and use it in GitHub Desktop.
Canonical

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

Suppose I have a 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, as we have to hit the DOM on every iteration of the loop, AND we're using an unnecessary loop! A better way of tackling this is to use a documentFragment inside a forEach call on your array, which you can append all of your new elements to before hitting the DOM, meaning you only have to hit it once.

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');
var docFrag = document.createDocumentFragment();


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

container.appendChild(docFrag);

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