Using JS to implement jQuery addClass removeClass hasClass function function

  • 2020-03-30 04:12:03
  • OfStack

Without further ado, go straight to the code


function addClass(obj, cls){
    var obj_class = obj.className,//Gets the class content.
    blank = (obj_class != '') ? ' ' : '';//



    added = obj_class + blank + cls;//Combine the original class with the class to be added.
    obj.className = added;//Replace the original class.
}
 
function removeClass(obj, cls){
    var obj_class = ' '+obj.className+' ';//Gets the class content and adds a space at the beginning and end.             BCD '-> 'abc              BCD '< br / >     obj_class = obj_class.replace(/(s+)/gi, ' '),//Replace the extra empty character with a space.             BCD '-> 'ABC BCD '
    removed = obj_class.replace(' '+cls+' ', ' ');//Replace the class with a space before and after the original class. Ex) 'ABC BCD' -> 'BCD' < br / >     removed = removed.replace(/(^s+)|(s+$)/g, '');//Ex) 'BCD' -> 'BCD' < br / >     obj.className = removed;//Replace the original class.
}
 
function hasClass(obj, cls){
    var obj_class = obj.className,//Gets the class content.
    obj_class_lst = obj_class.split(/s+/);//


    x = 0;
    for(x in obj_class_lst) {
        if(obj_class_lst[x] == cls) {//Loop through the array to determine whether CLS
is included             return true;
        }
    }
    return false;
}


Related articles: