How do I add a class to a given element?

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

I have an element that already has a class:

25条回答
  •  被撕碎了的回忆
    2020-11-21 12:06

    To add an additional class to an element:

    To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

    document.getElementById("MyElement").className += " MyClass";
    

    To change all classes for an element:

    To replace all existing classes with one or more new classes, set the className attribute:

    document.getElementById("MyElement").className = "MyClass";
    

    (You can use a space-delimited list to apply multiple classes.)

提交回复
热议问题