jQuery Extension: removeClassExcept() method

I came across a question on StackOverflow.com where the user wanted the ability to remove all classes from an element except certain ones.  For example if I had the following element

<div class="aa bb cc dd ee">Lorem Ipsum</div>

How would you go about removing all classes except for “aa” and “bb”?  One way would be to just set the class attribute to the classes you wanted to keep.


$("div").attr("class", "aa bb");

That’s easy enough.  Another way would be to use some built in jQuery methods.


$("div").removeClass().addClass("aa bb");

The previous code would remove all classes and then add back the ones that were needed.  That snippet could be put into a jQuery extension to make it easier to call.


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

$("div").removeClassExcept("aa bb");

That makes the code look cleaner.  One problem both of these solutions have is they don’t check to see if the class already exists before adding it.  On the Stack Overflow question, Brad Christie proposed a solution to handle the case where you didn’t want to add a class unless it already existed.  The updated extension now takes that into consideration.


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 i = 0; i < keep.length; i++){
            if ($el.hasClass(keep[i])) reAdd.push(keep[i]);
         }

         // drop all, and only add those confirmed as existing
         $el
            .removeClass()               // remove existing classes
            .addClass(reAdd.join(' '));  // re-add the confirmed ones
    });
};

Here is a jsFiddle showing the use of removeClassExcept(): http://jsfiddle.net/9xhND/1/

Advertisements
jQuery Extension: removeClassExcept() method

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s