How do I add a class to a given element?

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

I have an element that already has a class:

25条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 11:54

    The easiest way to do this without any framework is to use element.classList.add method.

    var element = document.getElementById("div1");
    element.classList.add("otherclass");
    

    Edit: And if you want to remove class from an element -

    element.classList.remove("otherclass");
    

    I prefer not having to add any empty space and duplicate entry handling myself (which is required when using the document.className approach). There are some browser limitations, but you can work around them using polyfills.

提交回复
热议问题