开发者

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

开发者 https://www.devze.com 2023-03-01 06:43 出处:网络
I need to set the class for an element in my page. With plain JavaScript, I would write something like:

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

document.getElementById('foo').className = 开发者_如何学Go"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?


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');


Set the class attribute directly using .attr():

$('#foo').attr('class', 'my_class');


You could use the .attr() function like so:

$('#foo').attr('class', 'my_class');


You could use that:

$('#foo').attr('class', 'my_class');

It will replace any class with "my_class"


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


Ah, found the answer just seconds after I posted the question. Apparently my Google skills were insufficient... :-(

At any rate, the answer is in the removeClass() function. So, you can do:

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

Couldn't be simpler.


you can try using .toggleClass()

0

精彩评论

暂无评论...
验证码 换一张
取 消