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
jQuery Manipulating CSSaddClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements. css() - Sets or returns the style attribute.
jQuery removeClass() MethodThe removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected elements.
Which jQuery method is used for adding/removing one or more classes from selected elements ? The method used for adding or removing the class to an element is the toggleClass() method.
As of jQuery 1.4, the . removeClass() method allows us to indicate the class to be removed by passing in a function.
$(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.
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.
toggleClass
does what you would expect it to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With