This article is divided into two parts for explanation, the specific content is as follows
Part 1: Native js implementation of addClass, removeClass, hasClass methods
function hasClass(elem, cls) { cls = cls || ''; if (cls.replace(//s/g, '').length == 0) return false; //When cls has no parameters, return new RegExp(' + cls + ' ').test(' ' + elem.className + ' ');}function addClass(ele, cls) { if (!hasClass(elem, cls)) { ele.className = ele.className == '' ? cls : ele.className + ' ' + cls; }}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, hasClass function function
function addClass(obj, cls){ var obj_class = obj.className,//Get class content. blank = (obj_class != '') ? ' ' : '';//Defend whether the obtained class is empty, if it is not empty, add a 'space' in front of it. added = obj_class + blank + cls;//Combining the original class with the class that needs to be added. obj.className = added;//Replace the original class.} function removeClass(obj, cls){ var obj_class = '+obj.className+' ';//Get 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 the extra empty characters with a space. ex) ' abc bcd ' -> ' abc bcd ' removed = obj_class.replace(' '+cls+' ', ' ');//Replace the class with spaces at the beginning and end in the original class. ex) ' abc bcd ' -> 'bcd ' removed = removed.replace(/(^/s+)|(/s+$)/g, '');//Remove the beginning and end spaces. 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 into an array through split empty characters. x = 0; for(x in obj_class_lst) { if(obj_class_lst[x] == cls) {//Loop the array and determine whether it contains cls return true; } } return false;}The above is all about this article, I hope it will be helpful for everyone to learn JavaScript programming.