如何将类添加到给定的元素? [英] How to 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>
现在,我想创建一个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.
另请参见 MDN上的element.className .
这篇关于如何将类添加到给定的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!