This article mainly introduces the native js Implementation of addClass, removeClass, hasClass methods and the use of native JS to implement jQuery's addClass, removeClass, and hasClass functions, for more information, see the following section.
Part 1:Native js implements addClass, removeClass, and hasClass Methods
Function hasClass (elem, cls) {cls = cls | ''; if (cls. replace (/\ s/g ,''). length = 0) return false; // If cls does not have a parameter, false return new RegExp (''+ cls +'') is returned ''). test (''+ elem. className + '');} function addClass (ele, cls) {if (! HasClass (elem, cls) {ele. className = ele. className = ''? Cls: ele. className + ''+ cls;} function removeClass (ele, 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 ,'');}}
Part 2:Use native JS to implement jQuery's addClass, removeClass, and hasClass Functions
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, // get 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 ;}
The above is all the content of this article, and I hope it will help you learn javascript programming.