PHPDev76
PHPDev76

Reputation: 161

jquery .each() add individual attribute to a div

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

Answers (3)

Fiddle DEMO

$(".slide").each(function (index) {
    $(this).data('slide', index);
});

Updated Fiddle DEMO

$(".slide").each(function (index) {
    $(this).attr('data-slide', index+1);
});

Upvotes: 2

Arun P Johny
Arun P Johny

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

Rory McCrossan
Rory McCrossan

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

Related Questions