Reputation: 15231
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
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