0

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 ?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.