0

I currently have a page that has multiple elements with the class "chained". I want to use a class selector so that I can select all of these, and run some additional code based on some data attributes (which will be different for each element). My code so far is:

$('.chained_child').remoteChainedTo('chained_parent'
   + $(this).data('chained-parent'), $(this).data('chained-url'));

I believe the problem is with this part: $(this).data('chained-parent') - this does not appear to be working. How can I select the data attribute of the selected element?

Thanks!

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
Harry
  • 4,660
  • 7
  • 37
  • 65

3 Answers3

4

You can use the .each() method to iterate over the matched set of elements and run a function for each one:

$('.chained_child').each(function () {
    $(this).remoteChainedTo('chained_parent' + $(this).data('chained-parent'), $(this).data('chained-url'));
});

As you can see in the above code, inside the .each() callback this refers to the current underlying DOM node (not a jQuery object, hence the need to pass it to jQuery).

Note that some jQuery methods will accept a function as a single argument, which will be called once for each element in the matched set in an implicit .each() loop. Looking at the source of the plugin you're using shows that that's not the case here.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
2

I think you should use like this

$(".chained").each(function(){
//add data as you want
})
StaticVariable
  • 5,253
  • 4
  • 23
  • 45
0

Try using

$(this).attr('data-chained-parent')

OR

$(this).data('chainedParent')
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405