John Shaw
John Shaw

Reputation: 5

Count the number of elements with a specific class, then add an ID that numbers them

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>

Upvotes: 0

Views: 991

Answers (4)

Kieran
Kieran

Reputation: 6186

What you have is just fine if you just change:

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

to

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

Upvotes: 1

Esailija
Esailija

Reputation: 140210

$('.item').addClass(function(i){
    return "count" + (i + 1);
});

Upvotes: 1

labroo
labroo

Reputation: 2961

Try this

$('div.item').each(function(i,n){ $(n).addClass('count' + (i + 1));});

Upvotes: 2

GTSouza
GTSouza

Reputation: 365

Try this:

$('.item').each(function (i, e) { $(e).addClass('count' + i); });

Upvotes: 1

Related Questions