jQuery: filter and remove classes except one

Suppose that you have an element with multiple classes and you actually don't need all of them but just one specific class. .removeClass() needs specific values and if you call it without parameters, it will simply remove all classes from the element. So you need to filter classes and leave only the desired one. Let's see how to accomplish this task.

Here's a sample HTML element:

<div id="test" class="test evident highlight alert">Test</div>​

We can create a simple jQuery plugin that removes all classes except the class specified as parameter:

(function($) {
    $.fn.excludeClass = function($class) {
        var that = this;
        var element = that[0];
        var cls = element.className;
        var parts = cls.split(' ');

        for (var i = 0; i < parts.length; i++) {

            var part = parts[i];
            if (part != $class) {

                element.className = element.className.replace(part, '');

            }

        }


        return that;



    }
})(jQuery);

We use directly the className property because it's the fastest way to manipulate classes with JavaScript. This property is a space-separated list of string values, each one representing a different class. className is a live property, in the sense that once you remove a value from the list, all the attached CSS styles will be removed.

An example:

$('#test').click(function() {
    $(this).excludeClass('test');
});‚Äč

You can see the demo below.

Demo

Live demo

Articles