How do I add a class to a given element?

I have an element that already has a class:

<div class="someclass">
    <img ... id="image1" name="image1" />
</div>

Now I want to create a Javascript function that will add a class to the div (not replace, but add).

How can I do that?


Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.

<div id="div1" class="someclass">
    <img ... id="image1" name="image1" />
</div>

Then

var d = document.getElementById("div1");
d.className += " otherclass";

See also element.className on MDN.


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.


find your target element "d" however you wish and then:

d.className += ' additionalClass'; //note the space

you can wrap that in cleverer ways to check pre-existence, and check for space requirements etc..

链接地址: http://www.djcxy.com/p/48358.html

上一篇: 用两个滑块交互式绘制matplotlib图

下一篇: 如何将一个类添加到给定的元素?