Object.prototype.hasClass = function(className) {
var pattern = new RegExp('(^|\\s)' + className + '(\\s|$)'); //use this regexp
return pattern.test(this.className); //to check for the class
}
Object.prototype.addClass = function(className) {
if (!this.hasClass(className)) { //if the class isn't there already
this.className += (' ' + className); //append it to the end of the class list
}
}
Object.prototype.removeClass = function(className) {
var pattern = new RegExp('(^|\\s)' + className + '(\\s|$)'); //use this regexp
this.className = this.className.replace(pattern, ' '); //to make a search and replace by a blank space
basic example:
.smalltext {
font-size: 8px;
}
.bigtext {
font-size: 15px;
}
colorblue {
color: blue;
}
colorred {
color: red;
}
This is some text
var el = document.getElementById('someelement');
if (el.hasClass('colorred'))
el.removeClass('colorred');
el.addClass('colorblue');
//now the text in someelement is blue, but still has a size of 8px
el.removeClass('smalltext');
//now the text has the default size
el.addClass('bigtext');
//now it has 15 px