Read specific elements and add count to class name using jquery

How can I count the number of elements with a specific class and add a count to each one as a new class name using jquery?

$('.full-screen').each(function(i) {
    $(this).addClass('.full-screen-', i);
});

      

I want to create:

<div class="full-screen full-screen-1"></div>
<div class="full-screen full-screen-2"></div>
<div class="full-screen full-screen-3"></div>
<div class="full-screen full-screen-4"></div>
<div class="full-screen full-screen-5"></div>

      

+3


source to share


3 answers


You can do

$('.full-screen').each(function(i) {
    $(this).addClass('full-screen-'+(i+1));

});

      




$('.full-screen').each(function(i) {
    $(this).addClass('full-screen-'+(i+1));
    console.log($(this)[0].outerHTML)
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="full-screen full-screen-1"></div>
<div class="full-screen full-screen-2"></div>
<div class="full-screen full-screen-3"></div>
<div class="full-screen full-screen-4"></div>
<div class="full-screen full-screen-5"></div>
      

Run codeHide result


+1


source


Also you can use .addClass( function )

instead of using.each()

$('.full-screen').addClass(function(i) {
    return 'full-screen-'+(i+1);
});

      



$('.full-screen').addClass(function(i) {
    return 'full-screen-'+(i+1);
});
console.log($('.full-screen'))
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="full-screen"></div>
<div class="full-screen"></div>
<div class="full-screen"></div>
<div class="full-screen"></div>
<div class="full-screen"></div>
      

Run codeHide result


+1


source


try it

$(".full-screen").each(function((i){
    $(this).addClass("full-screen-" + (i+1));
});

      

0


source







All Articles