JQuery how to add multiple img srcs to array

My jQuery / JS is set up so that when the doc is loaded, it looks for all the img srcs and pushes them into an array:

var sliderImg = [];
sliderImg.push($('.thumbnail').children('img').attr('src'));

      

Then I have the code to notify the array about the click event:

$('.thumbnail').each(function() {
$(this).click(function() {
    alert(sliderImg);
});
});

      

However, this is only adding the first img src path, is it possible to add all of them?

Thank!

+3


source to share


3 answers


You can use each

;



$('.thumbnail').children('img').each(function() {
  sliderImg.push($(this).attr('src');
});

      

+2


source


According to the .attr()

documentation

Get the attribute value for the first element in a set of matched elements

So $('.thumbnail').children('img').attr('src')

only returns the original image of the first image.



You can use .each()

to iterate over images and alternately push sources:

var sliderImg = [];
$('.thumbnail').children('img').each(function() {
    sliderImg.push($(this).attr('src'));
});

      

+2


source


attr

the method, when used as a getter, returns the attribute of the first element in the set. If you want an array of all attributes, you need to iterate over all the elements. You can use a method each

or more convenient map

:

var sliderImg = $('.thumbnail').children('img').map(function() {
    return this.src;
}).get();

      

+1


source







All Articles