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.
7 Answers
Why don't you just replace the class attribute with the classes that you want like so
$('#yourElement').attr('class',"aa dd");
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
});
};
-
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 adde
class that never existed. Oct 19, 2011 at 18:51 -
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. Oct 19, 2011 at 18:53
.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..
});
-
-
@Benoît Most of the time the simplest answer is always the best answer.... KISS!! Oct 19, 2011 at 19:18
-
@Laurence Burke : yes but in your solution, if there is only aa class, it will add dd !– BenoîtOct 19, 2011 at 19:30
-
@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".... Oct 19, 2011 at 19:34
-
@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).– BenoîtOct 20, 2011 at 8:14
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.
-
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.) Oct 19, 2011 at 18:48
-
@DanDaviesBrackett: True, and that is what OP's example code shows :) Laurence has smarter answer though.– SarfrazOct 19, 2011 at 18:49
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/
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');
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
"aa dd"
enough?