truslivii.lev
truslivii.lev

Reputation: 701

add all data attr from element in array

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

Answers (2)

Arun P Johny
Arun P Johny

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

Felix
Felix

Reputation: 38102

You need to use $(this) to target current clicked div with class lightbox-trigger:

var image_src_arr = $(this).data('img-src');

Updated Fiddle

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();

Updated Fiddle

Upvotes: 2

Related Questions