This article mainly introduces how to use JS to implement jQuery's addClass, removeClass, and hasClass functions. If you need a friend, you can refer to the following nonsense and directly go to the code.
The Code is as follows:
Function addClass (obj, cls ){
Var obj_class = obj. className, // obtain the class content.
Blank = (obj_class! = '')? '':''; // Determines whether the obtained class is empty. If not, add a 'space' to the front '.
Added = obj_class + blank + cls; // combines 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 +''; // obtain the class content and add a space at the beginning and end. ex) 'abc bcd'-> 'abc bcd'
Obj_class = obj_class.replace (/(\ s +)/gi, ''), // replace unnecessary null characters with a space. ex) 'abc bcd'-> 'abc bcd'
Removed = obj_class.replace (''+ cls +'', ''); // Replace the class with spaces at the beginning and end of the original class. ex) 'abc bcd'-> 'bcd'
Removed = removed. replace (/(^ \ s +) | (\ s + $)/g, ''); // remove spaces at the beginning and end. ex) 'bcd'-> 'bcd'
Obj. className = removed; // replace the original class.
}
Function hasClass (obj, cls ){
Var obj_class = obj. className, // obtain the class content.
Obj_class_lst = obj_class.split (/\ s +/); // convert cls to an array using the empty characters of split.
X = 0;
For (x in obj_class_lst ){
If (obj_class_lst [x] = cls) {// a loop array to determine whether the array contains cls
Return true;
}
}
Return false;
}