bba
bba

Reputation: 15231

jquery removing a class (if it exists and adding a new class)

I'm trying use jquery to remove a class from an element (not knowing ahead of time if it exists) and add a new element to replace it.

Would this be the best way (I'm skepticle because its not checking to see if the class exists before removing it):

$(elem).removeClass(oldClass).addClass(newClass);

thanks

Upvotes: 15

Views: 33169

Answers (3)

Surreal Dreams
Surreal Dreams

Reputation: 26380

$(elem).removeClass(oldClass).addClass(newClass);

This is perfect. No need to check first; if it's there, it goes, if not, it's already gone.

FYI, you can also toggleClass() and add/remove a class depending on if it's already there or not.

Upvotes: 31

NimChimpsky
NimChimpsky

Reputation: 47280

toggleClass 

does what you would expect it to do.

Upvotes: 4

Sarfraz
Sarfraz

Reputation: 382656

You can use hasClass:

if ($(elem).hasClass(oldClass)){
   // it has class
} else {
   // it doesn't have specified class
}

Description: Determine whether any of the matched elements are assigned the given class.

Upvotes: 10

Related Questions