jQuery removeClass() but not certain classes
Asked Answered
F

7

10

How can I do remove all classes from an element except certain classes. I'm assuming we can't use not with removeClass(). Let say I have a <div class="aa bb cc dd ee ff"></div> and I want to remove all classes except aa dd. How can I do this.

Frisk answered 19/10, 2011 at 18:41 Comment(2)
Isn't just setting the class to "aa dd" enough?Counterman
@pinkie any of these answers helpful???Ennui
E
17

Why don't you just replace the class attribute with the classes that you want like so

$('#yourElement').attr('class',"aa dd");
Ennui answered 19/10, 2011 at 18:45 Comment(0)
S
9

To make it a little cleaner, you could create a little extension.

jQuery.fn.removeClassExcept = function (val) {
    return this.each(function () {
        $(this).removeClass().addClass(val);
    });
};

Then you could use it like

$("selector").removeClassExcept("aa dd");

Heres an example: http://jsfiddle.net/9xhND/

UPDATE

Using Brad Christie's logic, the update will now only keep classes that were originally there and not add new classes. http://jsfiddle.net/9xhND/1/

jQuery.fn.removeClassExcept = function (val) {
    return this.each(function (index, el) {
        var keep = val.split(" "),  // list we'd like to keep
        reAdd = [],          // ones that should be re-added if found
        $el = $(el);       // element we're working on
        // look for which we re-add (based on them already existing)
        for (var c = 0; c < keep.length; c++){
          if ($el.hasClass(keep[c])) reAdd.push(keep[c]);
        }

        // drop all, and only add those confirmed as existing
        $el
          .removeClass()               // remove existing classes
          .addClass(reAdd.join(' '));  // re-add the confirmed ones
    });
};
Scrawny answered 19/10, 2011 at 18:47 Comment(2)
This add-in mixed with my logic would be the perfect solution. I fear though that <div class="a b c d f"> and $('div').removeClassExcept('d e') would add e class that never existed.Windup
You are right. "e" would be added if it wasn't there before. For op's case it may not matter. I will add an update to have both versions available.Scrawny
L
7

.removeClass() accepts as a parameter a function that will return which classes to actually remove..

so

$('div').removeClass(function(i, class){
    // variable class hold the current value of the class attribute
    var list = class.split(' '); // we create an array with the classes
    return  list.filter(function(val){ // here we remove the classes we want to keep
        return (val != 'aa' && val != 'dd');
    }).join(' '); // and return that list as a string which indicates the classes to be removed..
});
Lancaster answered 19/10, 2011 at 18:57 Comment(5)
I like this solution. More pretty than remove all class.Evangelin
@Benoît Most of the time the simplest answer is always the best answer.... KISS!!Ennui
@Laurence Burke : yes but in your solution, if there is only aa class, it will add dd !Evangelin
@Benoît in the different discussions in different answers we talk about this.. The OP did not specify that the class needs to be kept only if it is already present. If that was the case than the OP would not have selected my answer as the correct one. But not to say in different cases that my answer would be better than other posted here. Which goes back to my previous comment of "Most of the time"....Ennui
@Laurence Burke : the question was "I want to remove all classes except aa dd.". Your answer don't do that. Maybe your answer is adequate for Pinkie (then the question was not the good one, and if someone else have the same question, your answer will not help him).Evangelin
I
4

You can remove all and add needed ones back:

$('#divID').removeClass()
   .addClass('aa dd'); // add multiple classes by separating with space

Note: Calling removeClass() without specifying specific class name removes all classes.

Imagination answered 19/10, 2011 at 18:43 Comment(2)
This assumes that both aa and dd are present in the original. Keeping just them requires a bit more work (just checking which is there, and adding them back only if they were previously present.)Bloomy
@DanDaviesBrackett: True, and that is what OP's example code shows :) Laurence has smarter answer though.Imagination
F
4

jQuery actually provides a callback parameter to the removeClass method, so you could use a simple javascript regular expression to return all the classes except the ones you don't want to remove:

$('#myDiv').removeClass(function() {
    return $(this).attr('class').replace(/aa|bb/g, '');
});

This way you don't add classes 'aa' and 'bb' if they don't already exist.

You can see it in action here: http://jsfiddle.net/sr86u/3/

Fibrin answered 19/10, 2011 at 19:25 Comment(0)
F
2

One way you can do it is to just overwrite all classes with the class(es) you want to keep. So, if your div has an id of "myDiv", then you could do:

$('#myDiv').attr('class', 'aa dd');
Fibrin answered 19/10, 2011 at 18:46 Comment(0)
W
2

If you know what classes you want to keep you can just re-add them (as others have already shown).

I'll assume though that it's not known whether those classes are already applied, so I'll take it a step further:

var keep = ['aa','bb'],  // list we'd like to keep
    reAdd = [],          // ones that should be re-added if found
    $el = = $(el);       // element we're working on

// look for which we re-add (based on them already existing)
for (var c = 0; c < keep.length; c++){
  if ($el.hasClass(keep[c])) reAdd.push(keep[c]);
}

// drop all, and only add those confirmed as existing
$el
  .removeClass()               // remove existing classes
  .addClass(reAdd.join(' '));  // re-add the confirmed ones
Windup answered 19/10, 2011 at 18:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.