4/7/2015 - 9:06 AM

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 = ['', '', '', ''];
var container = document.getElementById('imageContainer');

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

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 = ['', '', '', ''];
var container = document.getElementById('imageContainer');
var docFrag = document.createDocumentFragment();

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


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 = ['', '', '', ''];

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

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