user1117313
user1117313

Reputation: 1985

jQuery add CSS class

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.

Upvotes: 4

Views: 2773

Answers (4)

Apolo Reader
Apolo Reader

Reputation: 59

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

Code is

$('your class').removeClass();

Upvotes: 1

ShadowScripter
ShadowScripter

Reputation: 7369

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

Upvotes: 1

Riz
Riz

Reputation: 10246

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

or

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

Upvotes: 4

Teun Pronk
Teun Pronk

Reputation: 1399

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

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

Upvotes: 6

Related Questions