Home  >  Article  >  Web Front-end  >  Use JS to implement jQuery’s addClass, removeClass, and hasClass functions_javascript skills

Use JS to implement jQuery’s addClass, removeClass, and hasClass functions_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:32:341345browse

No further nonsense, let’s get straight to the code

Copy code The code is as follows:

function addClass(obj, cls){
var obj_class = obj.className,//Get class content.
Blank = (obj_class != '') ? ' ' : '';//Determine whether the obtained class is empty, if not, add a 'space' in front.
added = obj_class blank cls;//Combine the original class and 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 null character 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 leading and trailing spaces. ex) 'bcd ' -> 'bcd'
Obj.className = removed;//Replace the original class.
}

function hasClass(obj, cls){
var obj_class = obj.className,//Get class content.
Obj_class_lst = obj_class.split(/s /);//Convert cls into an array by splitting the null character.
x = 0;
for(x in obj_class_lst) {
If(obj_class_lst[x] == cls) {//Loop the array to determine whether it contains cls
             return true;
}
}
Return false;
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn