Add a class name to an element
Login or Register to Bookmark this snippet
This function adds a class name to an element, keeping the existing classes but checking if it is already there first.
e is the element id as string or object reference.
t is the class as string.
Requires xGetElementById (available on this site).
function addClassName(e,t) {
if (typeof e == "string") {
e = xGetElementById(e);
}
//code to change and replace strings
var ec = ' ' + e.className.replace(/^s*|s*$/g,'') + ' ';
var nc = ec;
t = t.replace(/^s*|s*$/g,'');
//check if not already there
if (ec.indexOf(' '+t+' ') == -1) {
//not found, add it
nc = ec + t;
}
//return the changed text!
e.className = nc.replace(/^s*|s*$/g,''); //trimmed whitespace
return true;
}
Added by JC on 12th November, 2007
There are no comments about this snippet.
You must be registered and logged in to post a comment.
Login here to post a comment