如何向给定元素添加类? [英] 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>
现在我想创建一个Javascript函数,它将一个类添加到 div
(不替换,但添加)。
Now I want to create a Javascript function that will add a class to the div
(not replace, but add).
我该怎么做?
推荐答案
将空格加上新类的名称添加到元素的 className
属性中。首先,在元素上放置 id
,这样您就可以轻松获得参考。
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";
另见 element.className 。
这篇关于如何向给定元素添加类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文