0

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!

2
  • Jayesh's answer is fine, so I won't post another response, but if you're curious, your method doesn't work because $('.formEntry')[i] returns the native DOM element, which doesn't have an addClass function. You could either do $('.formEntry').eq(i) or $($('.formEntry')[i]) to get the proper jQuery object that you can call addClass on. (the former is probably better) Commented Jul 5, 2016 at 12:54
  • @MatisLepik Oh I see now. Thanks for clarifying; been stuck on this for a while :) Commented Jul 5, 2016 at 13:00

4 Answers 4

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

You don't have to use each. addClass takes function as well.

$('formEntry').addClass(function(i) { return 'form' + (i+1) })

Comments

0

Use this code for add class dynamically in loop...

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

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

Comments

0

You can use slice() :

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

API JQuery

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.