I would like the ability to add a class to an element and not replace what classes are already there.
Here is my javascript so far:
function black(body) {
var item = document.getElementById(body);
if (item) {
item.className=(item.className=='normal')?'black':'normal';
}
}
That piece of javascript replaces the existing classes with black. If the class already is black then it is changed to normal.
I would like to somehow combine the script above with the script below script, which adds a class, instead of replacing all existing classes.
var item = document.getElementById("body");
item.className = item.className + " additionalclass";
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:
If you wanted to toggle between the
blackandnormalclasses without affecting any other classes on the specified object, you could do this: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: