Count the number of elements with a specific class, then add the identifier, which is their number

I am very new to this, just trying to collect fragments from other posts.

I'm not sure how to count the number of elements on a page, and then add a class to distinguish them from the 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>

conclusion:

<div class="item count1"></div>
<div class="item count2"></div>
<div class="item count3"></div>
0
source share
4 answers

try it

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

Try the following:

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

, , , :

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

to

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

Source: https://habr.com/ru/post/1678844/


All Articles