You can use the following set of functions to add and remove class names. Plain js, no library.
// Return true or false if el has className or not
function hasClassName (el, cName) {
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)');
return el && re.test(el.className);
}
// Add class to element if it doesn't have it already
function addClassName (el, cName) {
if (!hasClassName(el, cName)) {
el.className = trim(el.className + ' ' + cName);
}
}
// Remove className from element if it has it
function removeClassName(el, cName) {
if (hasClassName(el, cName)) {
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)','g');
el.className = trim(el.className.replace(re, ''));
}
}
// Remove leading and trailing whitespace, reduce remaining whitespace to
// a single character
function trim(s) {
return s.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,' ');
}
To keep zzzzBov happy, here are the same function using a space instead of \s
(also removed reliance on the RegExp constructor so should be faster too). I'd recommend sticking with \s
as I haven't seen any convincing argument not to, but make you're own choice.
// Return true or false if el has className or not
function hasClassName (el, cName) {
return (' ' + el.className + ' ').indexOf(' ' + cName + ' ') != -1;
}
// Add class to element if it doesn't have it already
function addClassName (el, cName) {
if (!hasClassName(el, cName)) {
el.className = trimSpaces(el.className + ' ' + cName);
}
}
// Remove className from element if it has it
function removeClassName(el, cName) {
if (hasClassName(el, cName)) {
el.className = trimSpaces((' ' + el.className + ' ').replace(' ' + cName + ' ', ' '));
}
}
// Remove leading and trailing whitespace, reduce remaining whitespace to
// a single character
function trimSpaces(s) {
return s.replace(/(^ +)|( +$)/g,'').replace(/ +/g,' ');
}