原生JS实现hasClass,addClass,removeClass

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(/[\t\r\n]/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}; 

  

转载于:https://www.cnblogs.com/wsir/p/5553720.html

你可能感兴趣的:(原生JS实现hasClass,addClass,removeClass)