1

In my markup I have two div with same class . I want to add two different class in each div .

My html code is look like

<div class="my-class">
    --Content--
</div>

<div class="my-class">
    --Content--
</div>

But I want that two div as

<div class="my-class class-1">
    --Content--
</div>

<div class="my-class class-2">
    --Content--
</div>

So , if there is with a class "my-class" , I want to add an addition class to div like class-(1 to N) , How can I do this ?

3
  • How are you adding your dynamically generated content? Commented Feb 4, 2015 at 8:09
  • 1
    A bit OT: are you using the class attribute for styling or to identify the DIV later on? If for identity purposes I would recommend giving each class an ID attribute rather than a class name using one of the techniques displayed in the answers below. Commented Feb 4, 2015 at 8:24
  • Possible duplicate stackoverflow.com/questions/12610686/… Commented Feb 4, 2015 at 8:29

4 Answers 4

2

How about something like this:

$('.my-class').each(function(ind, ele) {
    var id = (ind+1);
    $(ele).addClass('class-' + id);
});

Check out the fiddle

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

1 Comment

@MurtazaHussain ...what do you mean? How would you do it without each?
1
var c = 1;
$(".my-class").each(function(){
$(this).addClass("class-" + c);
c++;
});

2 Comments

You can use the iterator of your 'each' function
one issue that you may find with my solution is that jQuery's .each function is super slow. It is better to use JavaScript for loop. Either way, this is a solution that gets the job done in an easy way to understand.
0

This may be what you want.

var classes = document.querySelectorAll('.my-class');
for(var i=0;i<classes.length;i++){
    classes[i].classList.add('class-'+i); 
    //classes[i].className += 'class-'+i; -> older browsers
}

Comments

0

I would also use .each() function, here is jsfiddle for example.

$(".my-class").each(function(i) {
 $(this).addClass("yourClass"+(i+1));
});

This will do the magic.

Hope it helps

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.