Extending jQuery: the removeAttributes() method

This plugin for jQuery simply resets all attributes for a given element. It is as follows:

(function($) {

    $.fn.removeAttributes = function() {
    
       var attrs = this[0].attributes;
       
       for(var i=0; i<attrs.length; i++) {
       
           var $attr = attrs[i].nodeName;
    
    
    
    switch($attr) {
    
        case 'class':
            this[0].className = '';
     break;
        case 'border':
            this[0].setAttribute('border', 0);
     break;
    
        default:
           this[0].setAttribute($attr, '');
    break;
    
    }
       
       
       }
    
    
    };


})(jQuery);

Example:

$('table').removeAttributes();

We work with the DOM element node to make sure that we have access to the attributes collection. Some things need still to be tested, particularly those attributes with numeric values. Here we use the className property to fix an obtuse bug of IE 6 with the setAttribute() method. You can see a demo here and download the source code here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

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