nutellasandwich nutellasandwich - 4 months ago 12
jQuery Question

Dynamically adding classes to a specific instance of another class

I'm trying to add a class to a specific instance of another class, while modifying the name of the class. This is the code i have:

for(var i = 0; i<3; i++){
$('.formEntry')[i].addClass("form" + i);
}


This is the code before the function is ran:

<fieldset class = "formEntry"></fieldset>
<fieldset class = "formEntry"></fieldset>
<fieldset class = "formEntry"></fieldset>


and this is the desired output.

<fieldset class = "formEntry form1"></fieldset>
<fieldset class = "formEntry form2"></fieldset>
<fieldset class = "formEntry form3"></fieldset>


Please help!

Answer

You can use .each() for loop through all elements and add class using .addClass() method.

$(document).ready(function() {
 $(".formEntry").each(function(i) {
       $(this).addClass("form" + (i+1));
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<fieldset class = "formEntry"></fieldset>
<fieldset class = "formEntry"></fieldset>
<fieldset class = "formEntry"></fieldset>

Comments