Bob Benedict
Bob Benedict

Reputation: 467

How do I find data attributes for images in a jQuery function?

I need to use jQuery to manipulate a bunch of images I show on the page that have an added html5 data attribute. How would I get the data values for value1 and value2 for all the images that have them, but ignore any image that does not. In other words, I need to cycle through all images on a page looking for the presence of these attributes.

Here's the code that displays the images:

<% @pictures.each do |picture| %>
  <%= link_to image_tag(picture.photo.url(:full),  
              :class => "picture_list_item",
              :data => {:value1 => picture.value1, :value2 => picture.value2}, 
              :id => "picture_" + picture.id.to_s),
              picture_path(:id => picture.id) %>
<% end %>

Upvotes: 1

Views: 426

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

$('#parent img[data]').each(function(){
       var data = $(this).attr('data').split(',');
       var data_1 = data[0];                         // retrieve first data
       var data_2 = data[1];                         // retrieve second data
       console.log( data_1 +' '+ data_2 );           // or use 'alert' to test
});

jsFiddle demo

.each()
.attr()
.split()

Upvotes: 0

Surreal Dreams
Surreal Dreams

Reputation: 26380

jQuery should make this pretty painless.

$("img[data]").each(function(){
    //do something with each individual image.
});

Or just this:

$("img[data]").doSomething();
//doSomething to all.

This should select all images with a data attribute. You can work with all of them at once, or use .each() to work with the selected images one at a time.

Here's a fiddle to demonstrate: http://jsfiddle.net/SLdk4/1/

Upvotes: 2

KoU_warch
KoU_warch

Reputation: 2150

I would suggest that you add a class representing each of those values and then can you manipulate them using class selectors.

Upvotes: 0

Related Questions