4

I want to remove a css class before adding a new class to an element. If I know which exact class the element has already, I can remove that by

$('#test').removeClass('current_class').addClass('new_class');

But the problem is that #test does not have always same class. So I would like to remove any css class attached attached to #test before adding before adding a new one. How should I do that? Thanks.

asked Apr 5, 2012 at 9:28
1
  • 2
    It always helps to read the docs - .removeClass() Commented Apr 5, 2012 at 9:32

4 Answers 4

6
$('#test').removeClass();

Will remove any class that the item has you can simply add your new class after that like you are doing now

answered Apr 5, 2012 at 9:29

Comments

4
$('#test').attr('class', '').addClass('new_class');

or

$('#test').removeClass().addClass('new_class');
answered Apr 5, 2012 at 9:29

Comments

1

How many different classes do you have?!

You could make a distinct check for each class

var not_allowed = ["class_1", "class_2", "class_3"];
for(i = 0; i < not_allowed.length; i++){
 if($("#test").hasClass(not_allowed[i])) $("#test").removeClass(not_allowed[i])
}
$("#test").addClass("new_class");

Or you could remove all classes at once with .removeClass() without any parameters and then add the new class

$("#test").removeClass().addClass("new_class");
answered Apr 5, 2012 at 9:35

Comments

1

Firstly remove all the classes using jQuery's removeClass() function and then add the classes according to your need.

Code is

$('your class').removeClass();
marc_s
759k185 gold badges1.4k silver badges1.5k bronze badges
answered Apr 5, 2012 at 11:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.