0

I have the sources for images (the urls) stored in a jQuery array. I want to prepend each source from the array into it's own collection of tags. I have something like this:

var images = [link1,link2,link3,etc,etc];

$('.gallery').prepend();

but I don't know what to put in the .prepend().

I need each image individually inside something like this:

<label class="align"><img class="thumbnail" src=""+images+""/></label>

How do I go about this?

Joie
  • 141
  • 1
  • 12

3 Answers3

1

You could map over the array and return a jQuery object for each:

var images = ['link1','link2','link3','etc','etc'];

$('.gallery').prepend(images.map(function(image){
    return $('<img class="thumbnail" />').src(image).wrap('<label class="align">').parent();
}));

(See my writeup on why not to just do a simple HTML string, even though it might be easier.)

Community
  • 1
  • 1
Scimonster
  • 32,893
  • 9
  • 77
  • 89
1

You will create a simple template and prepend that template (DOM element) into your gallery class.

var images = [link1,link2,link3,etc,etc];
for( var i=0; i<images.length; i++){
  var temp = '<label class="align"><img class="thumbnail" src="'+images[i]+'"/></label>'
  $('.gallery').prepend(temp);
}

Does this work for what you need?

Liam Schauerman
  • 851
  • 5
  • 10
  • Upvote for a plain JS solution. Was updating my answer for a plain variant, not needed now. Plain JS is often (a lot) faster, specially with simple code – Martijn Dec 13 '14 at 18:53
0

If you use jQuery you can loop through the array with $.each() and add the images to a string of html:

var images = ['link1','link2','link3','etc','etc'];

var imagesHtml = '';
$.each(images, function(index,value){
    imagesHtml += '<label class="align"><img class="thumbnail" src="'+value+'" /></label>';
});
$('.gallery').prepend( imagesHtml );

You can add the images to the gallery in the each loop, but changes to the DOM (simplefied: the document/html) are expensive, this way you make a large string (it's not html at this point), and only perform 1 DOM update

Martijn
  • 15,791
  • 4
  • 36
  • 68