Check out these basic plain javascript functions designed for altering class names in pure javascript. These functions are crafted to specifically match entire class names and eliminate any extra spaces before or after the classnames:
function removeClass(elem, cls) {
var str = " " + elem.className + " ";
elem.className = str.replace(" " + cls + " ", " ").replace(/^\s+|\s+$/g, "");
}
function addClass(elem, cls) {
elem.className += (" " + cls);
}
function hasClass(elem, cls) {
var str = " " + elem.className + " ";
var testCls = " " + cls + " ";
return(str.indexOf(testCls) != -1) ;
}
function toggleClass(elem, cls) {
if (hasClass(elem, cls)) {
removeClass(elem, cls);
} else {
addClass(elem, cls);
}
}
function toggleBetweenClasses(elem, cls1, cls2) {
if (hasClass(elem, cls1)) {
removeClass(elem, cls1);
addClass(elem, cls2);
} else if (hasClass(elem, cls2)) {
removeClass(elem, cls2);
addClass(elem, cls1);
}
}
If you desire to switch between the black
and normal
classes without impacting any other classes on the specified object, you can accomplish it like this:
function black(id) {
var obj = document.getElementById(id);
if (obj) {
toggleBetweenClasses(obj, "black", "normal");
}
}
Check out a working example here: http://jsfiddle.net/jfriend00/eR85c/
If you wish to add the "black" class only if "normal" is not already present, you can do so with this function:
function black(id) {
var obj = document.getElementById(id);
if (obj && !hasClass(obj, "normal")) {
addClass(obj, "black");
}
}