Reputation: 701
I need to add all of the data attributes in an array
$('.lightbox-trigger').click(function (e) {
e.preventDefault();
e.stopPropagation();
var image_src_arr = $('.lightbox-trigger').data('img-src');
console.log(image_src_arr);
});
http://jsfiddle.net/v7E5g/2/
but I get data attribute only the first element.
What's wrong? How can I make it work ?
Upvotes: 0
Views: 103
Reputation: 388316
You can use .map(), when you use .data() as a getter then it will return the value from the first object in the calling set of objects
$('.lightbox-trigger').click(function (e) {
e.preventDefault();
e.stopPropagation();
var image_src_arr = $('.lightbox-trigger').map(function () {
return $(this).data('img-src');
}).get()
console.log(image_src_arr);
});
Demo: Fiddle
Upvotes: 3
Reputation: 38102
You need to use $(this)
to target current clicked div with class lightbox-trigger
:
var image_src_arr = $(this).data('img-src');
If you want to retrieve an array of src
attribute then you can use .map()
:
var image_src_arr = $('.lightbox-trigger').map(function () {
return $(this).data('img-src');
}).get();
Upvotes: 2