JS implementation of Class name addition and removal

Source: Internet
Author: User

Method 1: Use the ClassName property;

Method 2: Use the classlist API;

//used to match the existence or absence of a class namefunctionReg (name) {return NewRegExp (' (^|\\s) ' +name+ ' (\\s+|$) ');}//hasclass addclass removeclass toogleclassvarHasclass,addclass,removeclass;if(' Classlist 'inchdocument.documentelement) {Hasclass=function(obj,cname) {returnobj.classList.contains (CNAME);    }; AddClass=function(obj,cname) {obj.classList.add (CNAME);    }; Removeclass=function(obj,cname) {obj.classList.remove (CNAME);    }; Toggleclass=function(obj,cname) {obj.classList.toggle (CNAME); };}Else{hasclass=function(obj,cname) {returnreg (CNAME). Test (Obj.classname);    }; AddClass=function(obj,cname) {if(!hasclass (Obj,cname)) {Obj.classname=obj.classname+ ' +CNAME;    }    }; Removeclass=function(obj,cname) {obj.classname=obj.classname.replace (Reg (CNAME), ');    }; Toggleclass=function(obj,cname) {varToggle=hasclass (obj,cname)?Removeclass:addclass;    Toggle (Obj,cname); };}//truedocument.body.classList.toString () = = = Document.body.className;

Note: This method can only pass one class name at a time and cannot cascade operations, while the similar operation under jquery is capable of manipulating multiple class names.

So expand it:

//AddClassdomtokenlist.prototype.addclass=function(str) {Tts.split ("). ForEach (function(c) { This. Add (c); }.bind ( This)); return  This;}//Removeclassdomtokenlist.prototype.removeclass=function(str) {Tts.split ("). ForEach (function(t) { This. Remove (t); }.bind ( This)); return  This;}//Removeclassdomtokenlist.prototype.toggleclass=function(str) {Tts.split ("). ForEach (function(t) { This. Toggle (t); }.bind ( This)); return  This;}

JS implementation of Class name addition and removal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.