Add and remove class names based on JavaScript and remove class names using javascript
Method 1: Use the className attribute;
Method 2: Use the classList API;
// Function reg (name) {return new RegExp ('(^ | \ s)' + name + '(\ s + | $) ');} // hasClass addClass removeClass toogleClassvar hasClass, addClass, removeClass; if ('classlist' in document.doc umentElement) {hasClass = function (obj, cname) {return obj. classList. contains (cname) ;}; addClass = function (obj, cname) {obj. classList. add (cname) ;}; removeClass = function (obj, cname) {obj. classList. remove (cname) ;}; toggle Class = function (obj, cname) {obj. classList. toggle (cname) ;};} else {hasClass = function (obj, cname) {return reg (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) {var toggle = 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 perform cascade operations. Similar operations under jquery can operate on multiple class names.
So let's 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;}
The above section describes how to add and remove JavaScript implementation class names. I hope it will be helpful to you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!