Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all classes with jQuery?

Tags:

jquery

I have some up/down buttons that increase/decrease the size of the selected text by adding a class to the containing element, like

<span class="font20">Some text</span>

The font20 class sets font-size:20px, font21 sets font-size: 21, etc.

I have another button "Clear Formatting" that needs to remove any classes I added. I could go through and see if font20 is applied and remove it if it is. If not, see if font21 is applied and remove it if it is, etc. and go through 50 or so possibilities. But what I'd rather do is something like

jQuery('selector').removeClass("*");

That is, remove all classes that may have been added. The removeClass("*") above doesn't seem to work. Is there another way to remove all the classes applied to a selector, using jQuery?

Thanks.

like image 501
Steve Avatar asked May 07 '14 22:05

Steve


People also ask

How do I remove a class from all elements?

To remove all CSS classes of an element, we use removeClass() method. The removeClass() method is used to remove one or more class names from the selected element.

What is addClass and removeClass in jQuery?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.


2 Answers

Just use

jQuery('selector').removeClass();

to remove all the classes.

like image 83
Grégory OBANOS Avatar answered Oct 19 '22 08:10

Grégory OBANOS


From the documentation:

If a class name is included as a parameter, then only that class will be removed from the set of matched elements. If no class names are specified in the parameter, all classes will be removed.

So simply using:

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

will remove all classes from #whatever.

like image 8
Jane S Avatar answered Oct 19 '22 10:10

Jane S