/ Published in: JavaScript
                    
                                        
Element.prototype functions to manipulate element classes.
                
                            
                                Expand |
                                Embed | Plain Text
                            
                        
                        Copy this code and paste it in your HTML
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
Element.prototype.addClass = function $_addC(clas){
if(this.className && this.className !== '') { // it already has at least one class
if(!this.hasClass(clas)){
this.className = this.className+' '+clas;
}
} else { // it doesnt have any classes yet
this.className = clas;
}
}
Element.prototype.hasClass = function $_has(clas){
if((this.className.split(' ')).contains(clas)) return true;
return false;
}
Element.prototype.countClasses = function $_count(){
if(!this.className) return 0;
if(this.className.replace(' ') == this.className) return 1;
var listOf = this.className.split(' ');
return listOf.length;
}
Element.prototype.removeClass = function $_remove(clas){
if(this.hasClass(clas)){ // make sure it has the class we want to remove
if(this.countClasses() == 1) this.className = '';
else {
var reg = new RegExp('(\\s|^)'+clas+'(\\s|$)');
this.className=this.className.replace(reg,' ');
}
}
}
Element.prototype.toggleClass = function $_toggle(clas1){
if(this.hasClass(clas1)) this.removeClass(clas1);
else this.addClass(clas1);
}
Comments
 Subscribe to comments
                    Subscribe to comments
                
                