如何将类添加到给定元素? [英] How to add a class to a given element?

查看:51
本文介绍了如何将类添加到给定元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于如何将类添加到给定元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆