Manipulating classes in Javascript
Here's a set of functions to manipulate HTML element classes in Javascript that came out of a project to handle form input to output, all on the client side. As I've laid them out here each function is added to the Element object as a method using the prototype constructor. This means it's easy to check or manipulate an element's class like this:
el = document.getElementById("answer1");
el.switchClassName("small","big");
There are four methods here: hasClassName, addClassName, removeClassName and switchClassName. The first three take a single parameter, the class name, and returns true or false. switchClassName takes two parameters: fromClass and toClass, and returns true or false. No validation is done on the contents of the parameters provided.
Element.prototype.hasClassName = function(strClass) {
if ( this.className ) {
return (this.className.match(new RegExp("\\b"+strClass+"\\b","i")) != null);
}
return false;
}
Element.prototype.removeClassName = function(strClass) {
if ( this.className ) {
this.className = this.className.replace(new RegExp("\\b"+strClass+"\\b","i"),"").replace(/\s+$/,"");
return true;
}
return false;
}
Element.prototype.addClassName = function(strClass) {
if ( this.className ) {
if (!this.hasClassName(strClass)) {
this.className += " "+strClass;
return true;
}
} else {
this.className = strClass;
return true;
}
return false;
}
Element.prototype.switchClassName = function(fromClass, toClass) {
if ( this.className ) {
if (this.hasClassName(fromClass)) {
this.className = this.className.replace(new RegExp("\\b"+fromClass+"\\b","i"),toClass);
return true;
}
}
return false;
}