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.

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

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

Comments

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

or

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

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");

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.