Javascript – How to set the class for an element using jQuery? Don’t want to add/remove classes

cssjavascriptjquery

I need to set the class for an element in my page. With plain JavaScript, I would write something like:

document.getElementById('foo').className = "my_class";

This just sets the class, which is exactly what I want. But I'm using jQuery on my page and so would like to do this in a "jQuery way", since it seems weird to mix the old style and the jQuery style. But jQuery apparently only allows you use addClass() or removeClass(), like so:

$('#foo').addClass("my_class");

The problem is that it merely adds a class to the element, it does not replace the currently existing class. Does this mean I have to keep track of the old class and do a removeClass() first? Is there no way to tell jQuery to replace the current class no matter what it is and just replace it with a new one?

Best Answer

To remove all classes from an element:

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

Specifying no arguments to removeClass removes all the classes. So your solution would be:

$('#foo').removeClass().addClass('my_class');