Reputation: 15
I am trying to give each .scan a new class but with increasing count
What i have tried was using the each function from jQuery and then using $(this) but $(this) will allways contain only the class name so every .scan will be changed.
$( ".scan" ).each(function() {
i = 0;
$(this).addClass( "count"+i );
i++;
});
The Result was
<div class="scan count0"></div>
<div class="scan count0"></div>
But what i want is
<div class="scan count0"></div>
<div class="scan count1"></div>
Here is a Fiddle with my current state.
Every tipp/help is much appreciated.
Upvotes: 0
Views: 49
Reputation: 82241
i.e. because i is defined inside each method.You need to set i value outside each method:
var i = 0;
$( ".scan" ).each(function() {
$(this).addClass( "count"+i );
i++;
});
However you can use default argument parameter index of each function to give incremenetal class suffix:
$(".scan").each(function(i){
$(this).addClass("count" + i);
});
or use callback function of addClass()
method:
$(".scan").addClass(function(i){
return "count" + i;
});
Upvotes: 5