how to append a css class to an element by javascript?

前端 未结 7 1922
慢半拍i
慢半拍i 2020-12-14 14:09

Suppose a HTML element\'s id is known, so the element can be refereced using:

document.getElementById(element_id);

Does a nati

相关标签:
7条回答
  • 2020-12-14 14:40
    addClass=(selector,classes)=>document.querySelector(selector).classList(...classes.split(' '));
    

    This will add ONE class or MULTIPLE classes :

    addClass('#myDiv','back-red'); // => Add "back-red" class to <div id="myDiv"/>
    addClass('#myDiv','fa fa-car') //=>Add two classes to "div"
    
    0 讨论(0)
  • 2020-12-14 14:40

    you could use setAttribute.

    Example: For adding one class:

     document.getElementById('main').setAttribute("class","classOne"); 
    

    For multiple classes:

     document.getElementById('main').setAttribute("class", "classOne classTwo"); 
    
    0 讨论(0)
  • 2020-12-14 14:41

    Adding class using element's classList property:

    element.classList.add('my-class-name');
    

    Removing:

    element.classList.remove('my-class-name');
    
    0 讨论(0)
  • 2020-12-14 14:42

    When an element already has a class name defined, its influence on the element is tied to its position in the string of class names. Later classes override earlier ones, if there is a conflict.

    Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.

    document.addClass= function(el, css){
        var tem, C= el.className.split(/\s+/), A=[];    
        while(C.length){
            tem= C.shift();
            if(tem && tem!= css) A[A.length]= tem;
        }
        A[A.length]= css;
        return el.className= A.join(' ');   
    }
    
    0 讨论(0)
  • 2020-12-14 14:54

    You should be able to set the className property of the element. You could do a += to append it.

    0 讨论(0)
  • 2020-12-14 14:58

    classList is a convenient alternative to accessing an element's list of classes.. see http://developer.mozilla.org/en-US/docs/Web/API/Element.classList.

    Not supported in IE < 10

    0 讨论(0)
提交回复
热议问题