如何将类添加到给定元素?

2022-01-29 00:00:00 javascript dom-manipulation

我有一个元素已经有一个类:

I have an element that already has a class:

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

现在,我想创建一个 JavaScript 函数,它将向 div 添加一个类(不是替换,而是添加).

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

我该怎么做?

推荐答案

如果你只针对现代浏览器:

使用 element.classList.add 添加一个类:

element.classList.add("my-class");

和 element.classList.remove 删除一个类:

element.classList.remove("my-class");

如果您需要支持 Internet Explorer 9 或更低版本:

在元素的 className 属性中添加一个空格和新类的名称.首先,在元素上放一个id,这样你就可以很容易地获得参考.

If you need to support Internet Explorer 9 or lower:

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>

然后

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

注意otherclass之前的空格.包含空格很重要,否则它会损害类列表中位于它之前的现有类.

Note the space before otherclass. It's important to include the space otherwise it compromises existing classes that come before it in the class list.

另请参阅 element.className on MDN.

相关文章