简体   繁体   中英

How to removeClass with exception in jQuery

i have a little jQuery case. So, i want to remove all of block classes but with little exception - if this div/block have some classes every of them will be deleated but one specify not. I'v try something like this but it's not work.

$('#rounded_items').removeClass(function(){
    $('#rounded_items').not.getElementsByClassName('small_menu');
}).addClass('main_menu');

Can you help me?

It's a little unclear what exactly you're trying to do, but my best guess would be something like this:

$('#rounded_items:not(.small_menu)').removeClass().addClass('main_menu');

... which will replace all class names with just main_menu to all items with ID rounded_items (!!!) except those with class small_menu .

Do take note that IDs should be unique . Can't stress that enough. So it doesn't make sense to select by ID and expect multiple elements so that you can filter by class further.

ID's should be unique, so all you have to do is check that the single element you are targeting does not have the class before you remove the classes :

var isSmall = $('#rounded_items').is('.small_menu');
$('#rounded_items').attr('class', isSmall ? 'main_menu' : '');

Can't you just check if the object has this class which should not be removed. If it has it - remove all classes and add the needed class. Something like this:

if ($("#item").hasClass("neededClass")){
   $("#item").removeClass();
   $("#item").addClass("neededClass");
}

I'm not sure if this is what you want to do.

Use following code

$('#rounded_items').removeClass(function(){
     var el = $('.small_menu');
    $('#rounded_items').not(el);
}).addClass('main_menu');

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