0

I'm very new to this, just trying to piece together snippets from other posts.

I'm unsure how to count the number of elements on a page, then add a class to differentiate them with a number.

<script type="text/javascript">
$(document).ready(function(){
    $('.item').each(function (e) { $(this).addClass('count' + e); });
});
</script>

<div class="item"></div>
<div class="item"></div>
<div class="item"></div>

output to:

<div class="item count1"></div>
<div class="item count2"></div>
<div class="item count3"></div>
Filburt
  • 17,626
  • 12
  • 64
  • 115
John Shaw
  • 5
  • 3
  • 2
    What you have there should work (what you call "e" should be the index of the each loop, which should be exactly what you want); could you explain the problem you're having? – machineghost Jul 13 '12 at 21:45

4 Answers4

2

Try this

$('div.item').each(function(i,n){ $(n).addClass('count' + (i + 1));});
labroo
  • 2,901
  • 3
  • 27
  • 36
1

Try this:

$('.item').each(function (i, e) { $(e).addClass('count' + i); });
GTSouza
  • 365
  • 4
  • 16
1
$('.item').addClass(function(i){
    return "count" + (i + 1);
});
Esailija
  • 138,174
  • 23
  • 272
  • 326
1

What you have is just fine if you just change:

$(this).addClass('count' + e);

to

$(this).addClass('count' + (e + 1));
Kieran
  • 5,906
  • 3
  • 24
  • 34