<!DOCTYPE HTML><HTML><HeadLang= "en"> <MetaCharSet= "UTF-8"> <title>Addclass,removeclass,hasclass,toggleclass,getbyclass</title></Head><Body><Divclass= "Div1"ID= "Box1"></Div><inputtype= "button"value= "button"ID= "BTN1"/><Script> functionaddclass (obj,cls) {//obj: The element to add classname, CLS: the classname to add; //if the original class is not: if(Obj.classname== "') {Obj.classname=CLS; } Else { //there is already a class, new class situation: varArrclassname=Obj.className.split (' ');// varIndex=Arrindexof (ARRCLASSNAME,CLS); if(Index== -1) { //if the class that you want to add does not exist on the original element:Obj.classname+= ' ' +CLS; } } } functionArrindexof (arr,v) {//detects if the same value exists in the array and returns its position; for(varI=0; I<Arr.length;i++){ if(Arr[i]==v) { returni; } } return -1; } functionRemoveclass (obj,cls) {//If there is a class: if(Obj.classname!= "'){ varArrclassname=Obj.className.split (' ');//split the original class to see if it contains the class that needs to be removed, that is, the classname of the reference CLS; varIndex=Arrindexof (ARRCLASSNAME,CLS); //R If there is a class that needs to be removed if(Index!= -1) {arrclassname.splice (index,1); Obj.classname=Arrclassname.join ("'); } } } functionHasclass (obj,cls) {varCLS=CLS|| "'; if(Cls.replace (/\s/G,"'). Length== 0){ return false;//returns False when the CLS has no parameters; }Else{ return NewRegExp (' ' +CLS+ "'). Test (' ' +obj.classname); } } functionToggleclass (obj,cls) {hasclass (OBJ,CLS)?Removeclass (OBJ,CLS): AddClass (OBJ,CLS); } functionGetbyclass (oparent, sclass) {if(oparent.getelementsbyclassname) {returnOparent.getelementsbyclassname (Sclass); } Else { //IE 8 7 6 vararr= []; varReg= NewRegExp ('\\b' +Sclass+ '\\b'); varAele=Oparent.getelementsbytagname ('*'); for (varI= 0; I<aele.length; I++) { if(Reg.test (aele[i].classname)) {Arr.push (aele[i]); } } returnarr; } } varOBTN1=document.getElementById ('BTN1'); varOBox1=document.getElementById ('Box1'); Obtn1.onclick= function () { if(Hasclass (OBox1,'Div1') {alert ('Hasclass'); }; Alert (Getbyclass (document,'Div1'). length); }</Script></Body></HTML>
Native JavaScript implementations of the Addclass,removeclass,hasclass,toggleclass,getbyclass