检查元素是否包含 JavaScript 中的类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5898656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if an element contains a class in JavaScript?
提问by daGUY
Using plain JavaScript (not jQuery), Is there any way to check if an element containsa class?
使用普通的 JavaScript(不是 jQuery),有没有办法检查一个元素是否包含一个类?
Currently, I'm doing this:
目前,我正在这样做:
var test = document.getElementById("test");
var testClass = test.className;
switch (testClass) {
case "class1":
test.innerHTML = "I have class1";
break;
case "class2":
test.innerHTML = "I have class2";
break;
case "class3":
test.innerHTML = "I have class3";
break;
case "class4":
test.innerHTML = "I have class4";
break;
default:
test.innerHTML = "";
}
<div id="test" class="class1"></div>
The issue is that if I change the HTML to this...
问题是,如果我将 HTML 更改为此...
<div id="test" class="class1 class5"></div>
...there's no longer an exact match, so I get the default output of nothing (""
). But I still want the output to be I have class1
because the <div>
still containsthe .class1
class.
...不再有完全匹配,所以我得到的默认输出没有 ( ""
)。但我还是想输出为I have class1
,因为<div>
还包含了.class1
类。
回答by Felix Kling
Use element.classList
.contains
method:
使用方法:element.classList
.contains
element.classList.contains(class);
This works on all current browsers and there are polyfills to support older browsers too.
这适用于所有当前浏览器,并且也有支持旧浏览器的 polyfill。
Alternatively, if you work with older browsers and don't want to use polyfills to fix them, using indexOf
is correct, but you have to tweak it a little:
或者,如果您使用较旧的浏览器并且不想使用 polyfills 来修复它们,使用indexOf
是正确的,但您必须稍微调整一下:
function hasClass(element, className) {
return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1;
}
Otherwise you will also get true
if the class you are looking for is part of another class name.
否则,true
如果您要查找的类是另一个类名的一部分,您也会得到。
jQuery uses a similar (if not the same) method.
jQuery 使用类似(如果不相同)的方法。
Applied to the example:
应用于示例:
As this does not work together with the switch statement, you could achieve the same effect with this code:
由于这不能与 switch 语句一起使用,因此您可以使用以下代码实现相同的效果:
var test = document.getElementById("test"),
classes = ['class1', 'class2', 'class3', 'class4'];
test.innerHTML = "";
for(var i = 0, j = classes.length; i < j; i++) {
if(hasClass(test, classes[i])) {
test.innerHTML = "I have " + classes[i];
break;
}
}
It's also less redundant ;)
它也不那么多余;)
回答by developer
The easy and effective solution is trying .containsmethod.
简单有效的解决方案是尝试.contains方法。
test.classList.contains(testClass);
回答by John Slegers
In modern browsers, you can just use the contains
method of Element.classList
:
在现代浏览器中,您可以只使用以下contains
方法Element.classList
:
testElement.classList.contains(className)
Demo
演示
var testElement = document.getElementById('test');
console.log({
'main' : testElement.classList.contains('main'),
'cont' : testElement.classList.contains('cont'),
'content' : testElement.classList.contains('content'),
'main-cont' : testElement.classList.contains('main-cont'),
'main-content' : testElement.classList.contains('main-content')
});
<div id="test" class="main main-content content"></div>
Supported browsers
支持的浏览器
(from CanIUse.com)
(来自CanIUse.com)
Polyfill
填充物
If you want to use Element.classList
but you also want to support older browsers, consider using this polyfillby Eli Grey.
如果你想使用Element.classList
,但你也想支持旧的浏览器,可以考虑使用这种填充工具以礼灰色。
回答by Thought
Since he wants to use switch(), I'm surprised no one has put this forth yet:
由于他想使用 switch(),我很惊讶还没有人提出这个:
var test = document.getElementById("test");
var testClasses = test.className.split(" ");
test.innerHTML = "";
for(var i=0; i<testClasses.length; i++) {
switch(testClasses[i]) {
case "class1": test.innerHTML += "I have class1<br/>"; break;
case "class2": test.innerHTML += "I have class2<br/>"; break;
case "class3": test.innerHTML += "I have class3<br/>"; break;
case "class4": test.innerHTML += "I have class4<br/>"; break;
default: test.innerHTML += "(unknown class:" + testClasses[i] + ")<br/>";
}
}
回答by Grant Miller
Element.matches()
元素匹配()
element.matches(selectorString)
element.matches(selectorString)
According to MDN Web Docs:
根据MDN 网络文档:
The
Element.matches()
method returnstrue
if the element would be selected by the specified selector string; otherwise, returnsfalse
.
如果元素将被指定的选择器字符串选择,则该
Element.matches()
方法返回true
;否则,返回false
。
Therefore, you can use Element.matches()
to determine if an element contains a class.
因此,您可以使用Element.matches()
来确定一个元素是否包含一个类。
const element = document.querySelector('#example');
console.log(element.matches('.foo')); // true
<div id="example" class="foo bar"></div>
回答by Keval Bhatt
Here is a little snippet If you're trying to check wether element contains a class, without using jQuery.
这是一个小片段 如果您要检查元素是否包含一个类,而不使用 jQuery。
function hasClass(element, className) {
return element.className && new RegExp("(^|\s)" + className + "(\s|$)").test(element.className);
}
function hasClass(element, className) {
return element.className && new RegExp("(^|\s)" + className + "(\s|$)").test(element.className);
}
This accounts for the fact that element might contain multiple class names separated by space.
这说明了元素可能包含多个由空格分隔的类名的事实。
OR
或者
You can also assign this function to element prototype.
您还可以将此功能分配给元素原型。
Element.prototype.hasClass = function(className) {
return this.className && new RegExp("(^|\s)" + className + "(\s|$)").test(this.className);
};
And trigger it like this (very similar to jQuery's .hasClass()
function):
并像这样触发它(非常类似于jQuery的.hasClass()
功能):
document.getElementById('MyDiv').hasClass('active');
回答by Dementic
This is a little old, but maybe someone will find my solution helpfull:
这有点旧,但也许有人会发现我的解决方案有帮助:
// Fix IE's indexOf Array
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement) {
if (this == null) throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) return -1;
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) n = 0;
else if (n != 0 && n != Infinity && n != -Infinity) n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
if (n >= len) return -1;
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) if (k in t && t[k] === searchElement) return k;
return -1;
}
}
// add hasClass support
if (!Element.prototype.hasClass) {
Element.prototype.hasClass = function (classname) {
if (this == null) throw new TypeError();
return this.className.split(' ').indexOf(classname) === -1 ? false : true;
}
}
回答by KooiInc
A simplified oneliner:1
一个简化的oneliner:1
function hasClassName(classname,id) {
return String ( ( document.getElementById(id)||{} ) .className )
.split(/\s/)
.indexOf(classname) >= 0;
}
1indexOf
for arrays is not supported by IE (ofcourse). There are plenty of monkey patches to be found on the net for that.
1indexOf
表示数组不受 IE 支持(当然)。有很多猴子补丁可以在网上找到。
回答by David
回答by TheBlackBenzKid
I know there a lot of answers but most of these are for additional functions and additional classes. This is the one I personally use; much cleaner and much less lines of code!
我知道有很多答案,但其中大部分是针对附加功能和附加类的。这是我个人使用的一种;更干净,更少的代码行!
if( document.body.className.match('category-page') ) {
console.log('yes');
}