Here are several plain javascript functions you can use for manipulating class names in plain javascript. It takes a little extra work in these functions to match whole class names only and avoid any extra spaces before/after 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 wanted to toggle between the black and normal classes without affecting any other classes on the specified object, you could do this:
function black(id) {
var obj = document.getElementById(id);
if (obj) {
toggleBetweenClasses(obj, "black", "normal");
}
}
Working example here: http://jsfiddle.net/jfriend00/eR85c/
If you wanted to add the "black" class unless "normal" was already present, you could do this:
function black(id) {
var obj = document.getElementById(id);
if (obj && !hasClass(obj, "normal")) {
addClass(obj, "black");
}
}