Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the class for an element using jQuery? Don't want to add/remove classes

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?

like image 653
jbrendel Avatar asked Apr 27 '11 17:04

jbrendel


People also ask

How can I delete one class and add another class in jQuery?

Given an HTML element and the task is to add and remove multiple classes from it using JQuery. Approach: First select the element to which multiple classes will be added. Then use addClass() method to add multiple classes to the element and removeClass() method to remove multiple classes.

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.

How do you add a class using jQuery?

To add a new class, we use jQuery addClass() method. The addClass() method is used to add more classes and their attributes to each selected element. It can also be used to change the property of the selected element.

How do I select a specific class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.


1 Answers

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');
like image 102
kcbanner Avatar answered Oct 17 '22 20:10

kcbanner