-2

I need to have a data attribute added to every image on a page. This data images provides a lightbox functionality but since there so many images it would be nice to automate this by using Jquery.

So far I've played with the data attribute possibilities like:

$('.item a).attr('data-lightbox');

I have multiple images on a pages and all with the .item div should have the data attribute applied to. Am I thinking the right way?

Badger
  • 166
  • 4
  • 12

2 Answers2

3

This will do the job

$('.item img').attr('data-lightbox', 'value');

Devz
  • 603
  • 6
  • 18
2

You are using a getter method by only passing in the key as a parameter. You need to use a setter and pass in a key and value. The correct syntax is

$(selector).data(name,value)

Loop over the images and use the data() method

$("img").each(function() {
    $(this).data("lightbox", "value");
});

https://api.jquery.com/jquery.data/

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
  • This seems like the logic way to do it. It's not working however. I might add that there is NO data attribute present in the div tag. Basically it looks like: and needs to be – Badger Aug 03 '16 at 19:15