Extending jQuery: adding and removing multiple CSS classes

Adding and removing multiple CSS classes is not part of the jQuery core. So why don't we extend jQuery by allowing it to fulfill this task? The jQuery code required for this is incredibly simple:

(function($) {


    $.fn.addClasses = function(classes) {
    
        var classList = classes.split(',');
 
 for(var i=0; i<classList.length; i++) {
 
     this.addClass(classList[i]);
 
 }
    
    };
    
    $.fn.removeClasses = function() {
    
        var classAttr = this.attr('class');
 
 var classList = classAttr.split(/\s/);
 
 for(var i=0; i<classList.length; i++) {
 
     this.removeClass(classList[i]);
 
 }
    
    };



})(jQuery);

There are two new methods here: addClasses(classes) and removeClasses(). The former accepts a comma-separated list of CSS classes which will we added to a given element, while the latter removes completely multiple CSS classes from an element. Example:

$(document).ready(function() {

    $('#add-link').click(function() {
        
 $('#test').addClasses('foo, bar, baz');
 
         return false;
    
    });
    
    $('#remove-link').click(function() {
    
        $('#test').removeClasses();
 
        return false;
    
    });

});

You can see the live demo here and download this plugin here.

Leave a Reply

Note: Only a member of this blog may post a comment.