How do I add a class to a given element?

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

I have an element that already has a class:

相关标签:
25条回答
  • 2020-11-21 12:01

    find your target element "d" however you wish and then:

    d.className += ' additionalClass'; //note the space
    

    you can wrap that in cleverer ways to check pre-existence, and check for space requirements etc..

    0 讨论(0)
  • 2020-11-21 12:01

    Another approach to add the class to element using pure JavaScript

    For adding class:

    document.getElementById("div1").classList.add("classToBeAdded");
    

    For removing class:

    document.getElementById("div1").classList.remove("classToBeRemoved");
    
    0 讨论(0)
  • 2020-11-21 12:02
    document.getElementById('some_id').className+='  someclassname'
    

    OR:

    document.getElementById('some_id').classList.add('someclassname')
    

    First approach helped in adding the class when second approach didn't work.
    Don't forget to keep a space in front of the ' someclassname' in the first approach.

    For removal you can use:

    document.getElementById('some_id').classList.remove('someclassname')
    
    0 讨论(0)
  • 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
    	})
    }

    0 讨论(0)
  • 2020-11-21 12:03

    In my case, I had more than one class called main-wrapper in the DOM, but I only wanted to affect the parent main-wrapper. Using :first Selector (https://api.jquery.com/first-selector/), I could select the first matched DOM element. This was the solution for me:

    $(document).ready( function() {
        $('.main-wrapper:first').addClass('homepage-redesign');
        $('#deals-index > div:eq(0) > div:eq(1)').addClass('doubleheaderredesign');
    } );
    

    I also did the same thing for the second children of a specific div in my DOM as you can see in the code where I used $('#deals-index > div:eq(0) > div:eq(1)').addClass('doubleheaderredesign');.

    NOTE: I used jQuery as you can see.

    0 讨论(0)
  • 2020-11-21 12:05

    You can use the classList.add OR classList.remove method to add/remove a class from a element.

    var nameElem = document.getElementById("name")
    nameElem.classList.add("anyclss")
    

    The above code will add(and NOT replace) a class "anyclass" to nameElem. Similarly you can use classList.remove() method to remove a class.

    nameElem.classList.remove("anyclss")
    
    0 讨论(0)
提交回复
热议问题