Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 957
bba Avatar asked Nov 10 '10 13:11

bba


People also ask

Has class add and remove jQuery?

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.

Can you remove a class with jQuery?

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 to add and remove classes in selected element?

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.

Which jQuery function is used to remove an existing class from the Element?

As of jQuery 1.4, the . removeClass() method allows us to indicate the class to be removed by passing in a function.


3 Answers

$(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.

like image 150
Surreal Dreams Avatar answered Oct 11 '22 21:10

Surreal Dreams


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.

like image 10
Sarfraz Avatar answered Oct 11 '22 23:10

Sarfraz


toggleClass 

does what you would expect it to do.

like image 4
NimChimpsky Avatar answered Oct 11 '22 23:10

NimChimpsky