Tell me how to write a selector to remove all classes except for certain

  • What exactly is causing you difficulty? why you do not like removeClass() ? - Alex

2 answers 2

 var requireClasses = ['selector', 'test']; $('.selector').removeClass(function (i, classNames) { // Если className не тот, что нам нужно оставить return classNames.split(' ').filter(function (className) { return requireClasses.indexOf(className) === -1; }).join(' '); }); 
  • 1 - if you want to remove all classes except for a specific one, then it is better to hang the handler on the given class or id 2 - Your code removes all classes jsfiddle.net/16kmvm3v - Alex
  • but everything is deleted because in the className parameter - the contents of the class attribute come - and not all classes are taken one by one - Grundy
  • yes sure ... well then ... - Pleshevskiy
  • it's better not to map, but filter - because it is filtering here - Grundy
  • @Pleshevskiy, besides this, in the statement of the problem - remove all classes except for certain , i.e. there may be several of them. - Alex

One solution could be: deleting all classes and adding those that should remain again

 $('.selector').removeClass().addClass('all needed classes'); 
  • the easiest and surest way) - Alex
  • @Alex, I’m afraid if animation classes with transitions are hung up, there may not be exactly the expected result :) - Grundy
  • I think it will fit just right) - quaresma89
  • Well, there is no code in the question and add. conditions, too, so there can be no complaints to you) - Alex