简体   繁体   中英

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?

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

使用.attr()直接设置class属性:

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

您可以像这样使用.attr()函数:

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

你可以尝试使用.toggleClass()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM