如何在 JavaScript 中检查 DOM 元素是否包含类?
如何在 JavaScript 中检查 DOM 元素是否包含类?
我尝试了以下代码,但由于某种原因它不起作用......
if (document.getElementById('element').class == "class_one") {
//code...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
要获取类属性的完整值,请使用
.className
From MDC:
自2013年起,你会得到额外的帮助。
许多年前,当这个问题首次得到解答时,
.className
是纯 JavaScript 中唯一真正的解决方案。自 2013 年起,所有浏览器都支持.classList
接口。JavaScript:
您还可以使用
classList
做一些有趣的事情,例如.toggle()
、.add()
和.remove()
。MDN 文档。
向后兼容代码:
To get the whole value of the class atribute, use
.className
From MDC:
Since 2013, you get an extra helping hand.
Many years ago, when this question was first answered,
.className
was the only real solution in pure JavaScript. Since 2013, all browsers support.classList
interface.JavaScript:
You can also do fun things with
classList
, like.toggle()
,.add()
and.remove()
.MDN documentation.
Backwards compatible code:
您需要的属性是
className
,而不是class
。另外,一个元素可以有很多类,所以如果你想测试它是否有一个特定的类,你需要执行如下操作:UPDATE
现代浏览器(几乎所有主要的浏览器,除了 IE <= 9) 支持
classList
属性,如 @Dropped.on.Caprica 的回答中所述。因此,在可能的情况下使用它是有意义的。下面是一些示例代码,用于检测浏览器是否支持classList
并回退到基于正则表达式的代码:The property you need is
className
, notclass
. Also, an element can have many classes, so if you want to test if it has a particular class you need to do something like the following:UPDATE
Modern browsers (pretty much everything major except IE <= 9) support a
classList
property, as mentioned in @Dropped.on.Caprica's answer. It therefore makes sense to use this where available. Here's some example code that detects whetherclassList
is supported by the browser and falls back to the regex-based code otherwise:所有现代浏览器都支持 contains 方法>
Element.classList
:演示
支持的浏览器
(来自 CanIUse.com)
Polyfill
如果你想使用
Element.classList
并且您还想支持 IE8 等古老的浏览器,请考虑使用 这个polyfill,作者:Eli Grey< /a>.All modern browsers support the
contains
method ofElement.classList
:Demo
Supported browsers
(from CanIUse.com)
Polyfill
If you want to use
Element.classList
and you also want to support ancient browsers like IE8, consider using this polyfill by Eli Grey.它是
.className
属性,如下所示:It's the
.className
property, like this:比所有这些(如果您使用的是 HTML5)更好的解决方案是使用 classList API。
A better solution than all of these (if you are using HTML5) is to use the classList API.
元素上的切换类
或
toggleClass on element
or
如果您使用 jQuery,那么这个简单的代码就会有所帮助:
如果您想检查页面中 2 个以上的类,则使用
$('.yourclass').length > 2
If you are using jQuery then just this simple code will help:
If you like to check more than 2 classes in the page then use
$('.yourclass').length > 2
hasClass:
containsClass:
codepen 演示
hasClass:
containsClass:
codepen demo