How do I add a class to a given element?

前端 未结 25 2384
清酒与你
清酒与你 2020-11-21 11:34

I have an element that already has a class:

25条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 12:03

    I too think that the fastest way is to use Element.prototype.classList as in es5: document.querySelector(".my.super-class").classList.add('new-class') but in ie8 there is no such thing as Element.prototype.classList, anyway you can polyfill it with this snippet (fell free to edit and improve it):

    if(Element.prototype.classList === void 0){
    	function DOMTokenList(classes, self){
    		typeof classes == "string" && (classes = classes.split(' '))
    		while(this.length){
    			Array.prototype.pop.apply(this);
    		}
    		Array.prototype.push.apply(this, classes);
    		this.__self__ = this.__self__ || self
    	}
    
    	DOMTokenList.prototype.item = function (index){
    		return this[index];
    	}
    
    	DOMTokenList.prototype.contains = function (myClass){
    		for(var i = this.length - 1; i >= 0 ; i--){
    			if(this[i] === myClass){
    				return true;
    			}
    		}
    		return false
    	}
    
    	DOMTokenList.prototype.add = function (newClass){
    		if(this.contains(newClass)){
    			return;
    		}
    		this.__self__.className += (this.__self__.className?" ":"")+newClass;
    		DOMTokenList.call(this, this.__self__.className)
    	}
    
    	DOMTokenList.prototype.remove = function (oldClass){
    		if(!this.contains(newClass)){
    			return;
    		}
    		this[this.indexOf(oldClass)] = undefined
    		this.__self__.className = this.join(' ').replace(/  +/, ' ')
    		DOMTokenList.call(this, this.__self__.className)
    	}
    
    	DOMTokenList.prototype.toggle = function (aClass){
    		this[this.contains(aClass)? 'remove' : 'add'](aClass)
    		return this.contains(aClass);
    	}
    
    	DOMTokenList.prototype.replace = function (oldClass, newClass){
    		this.contains(oldClass) && this.remove(oldClass) && this.add(newClass)
    	}
    
    	Object.defineProperty(Element.prototype, 'classList', {
    		get: function() {
    			return new DOMTokenList( this.className, this );
    		},
    		enumerable: false
    	})
    }

提交回复
热议问题