Reputation: 161
On load, i am looking to add a data-slide attribute number to each div found of the same class
for example:
<div class='slide' data-slide=''></div>
<div class='slide' data-slide=''></div>
<div class='slide' data-slide=''></div>
I am trying using the following code, however all it does is take the lnumber found rather than the index:
$( ".slide" ).each(function( index ) {
$('.slide').attr( 'data-slide',''+index+'');
});
I would like it to produce the following:
<div class='slide' data-slide='1'></div>
<div class='slide' data-slide='2'></div>
<div class='slide' data-slide='3'></div>
ANy ideas please?
Upvotes: 3
Views: 3403
Reputation: 57105
$(".slide").each(function (index) {
$(this).data('slide', index);
});
$(".slide").each(function (index) {
$(this).attr('data-slide', index+1);
});
Upvotes: 2
Reputation: 388316
The .attr() takes a function as the second argument which can return the values that has to be assigned to the attribute
$(".slide").attr('data-slide', function (index) {
return index + 1;
});
Demo: Fiddle
Upvotes: 9
Reputation: 337560
Inside the each()
block, this
will refer to the current element in the iteration.
$(".slide").each(function(index) {
$(this).attr('data-slide', index + 1);
});
Upvotes: 3