简体   繁体   中英

jquery allow only one of a group of classes on an element?

I have an element that gets a number of classes added to it + removed from it dynamically using jQuery. I'd like to ensure that I have only one of a set of classes on the element at a given time.

For example, I could have the .blue_element class that defines a font color, background color, border color, etc., and I wouldn't want that on the element at the same time as a .red_element class or a .yellow_element class, but I wouldn't mind it being on at the same time as a .small_element class or .big_element class.

Current method:

$('#target_element').removeClass('yellow_element').removeClass('red_element').addClass('blue_element')

This works fine but seems like it creates a risk for error, eg if I add a .purple_element class but forget to modify my removal code.

I'm doing this on a larger scale than in my example and may be adding and removing classes quite frequently, so I'd expect to make some boneheaded mistakes if I do it this way. Is there a more efficient way to do this?

Instead of using jQuery use native mathod

document.getElementById("target_element").className = 'blue_element';

Above code will remove all classes and keep/add only 'blue_element';

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