Class Manipulation
Three functions to help manipulate the class attribute of HTML elements.
hasClass( element, className )
This function checks element to see if it belongs to className and returns a boolean true or false.
addClass( element, className )
Use this to add className to the element.
removeClass( element, className )
Use this to remove className from the element.
function hasClass(el, sName) {
return !!(el && el.className && (' ' + el.className.replace(/\s+/g, ' ') + ' ').indexOf(' ' + sName + ' ') >= 0);
}
function addClass(el, className) {
if(!hasClass(el, className))
el.className += el.className ? ' ' + className : className;
}
function removeClass(el, className) {
if(hasClass(el, className)) {
var cn = [], ns = el.className.split(/\s+/), l = ns.length;
for(var i = 0; i < l; i++)
if(ns[i] != className)
cn.push(ns[i]);
el.className = cn.join(' ');
}
}
2008-05-17 -- Written by Woosta
Inspired by the code at http://phrogz.net/JS/AddClassKillClass_js.txt that we used to point people to, until someone pointed out that
it used \b to match existing classNames and that the functions had annoying names (starting with a capital is generally accepted to
indicate it's a function that can be used as an object constructor)
2008-05-17 -- Changed by Woosta
Changed to avoid the avoidance of regex.
2008-05-17 -- Changed by fatbrain
Removed extensive use of RegExp to increase performance. Credits to makk for suggesting some last minute performance tuning!
2008-07-14 -- Changed by makk
2 errors fixed in hasClass
2008-08-22 -- Changed by makk
Rewrite of hasClass