How do I add a class to a given element?

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

I have an element that already has a class:

25条回答
  •  眼角桃花
    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")
    

提交回复
热议问题