1、hasClass
function hasClass(elem, cls){ cls = cls || ''; if(cls.replace(/s/g, '').length == 0) return false; return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' '); }
2、addClass
function addClass(elem, cls){ if(!hasClass(elem, cls)){ elem.className += ' ' + cls; } }
3、removeClass
function removeClass(elem, cls){ if(hasClass(elem, cls)){ var newClass = ' ' + elem.className.replace(/[ ]/g, '') + ' '; while(newClass.indexOf(' ' + cls + ' ') >= 0){ newClass = newClass.replace(' ' + cls + ' ', ' '); } elem.className = newClass.replace(/^s+|s+$/g, ''); } }
//call the functions
addClass(document.getElementById("test"), "test");
removeClass(document.getElementById("test"), "test")
if(hasClass(document.getElementById("test"), "test")){//do something};