JavaScript CSS how to add and remove multiple CSS classes to an element

前端 未结 14 1957
迷失自我
迷失自我 2020-12-07 21:46

How can assign multiple css classes to an html element through javascript without using any libraries?

14条回答
  •  温柔的废话
    2020-12-07 22:24

    There are at least a few different ways:

    var buttonTop = document.getElementById("buttonTop");
    
    buttonTop.className = "myElement myButton myStyle";
    
    buttonTop.className = "myElement";
    
    buttonTop.className += " myButton myStyle";
    
    buttonTop.classList.add("myElement");
    
    buttonTop.classList.add("myButton", "myStyle");
    
    buttonTop.setAttribute("class", "myElement");
    
    buttonTop.setAttribute("class", buttonTop.getAttribute("class") + " myButton myStyle");
    
    buttonTop.classList.remove("myElement", "myButton", "myStyle");
    

提交回复
热议问题