什么是纯 JavaScript 的“hasClass”函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5085567/
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
What is the "hasClass" function with plain JavaScript?
提问by Kyle
How do you do jQuery's hasClass
with plain ol' JavaScript? For example,
你如何hasClass
使用普通的 JavaScript 来处理jQuery ?例如,
<body class="foo thatClass bar">
What's the JavaScript way to ask if <body>
has thatClass
?
询问 if <body>
has的 JavaScript 方式是thatClass
什么?
采纳答案by SLaks
You can check whether element.className
matches /\bthatClass\b/
.\b
matches a word break.
您可以检查是否element.className
匹配/\bthatClass\b/
。\b
匹配断字。
Or, you can use jQuery's own implementation:
或者,您可以使用 jQuery 自己的实现:
var className = " " + selector + " ";
if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" thatClass ") > -1 )
To answer your more general question, you can look at jQuery's source codeon github or at the source for hasClass
specifically in this source viewer.
要回答更一般的问题,您可以查看github上的 jQuery源代码或hasClass
在此源查看器中专门查看的源代码。
回答by Damien
Simply use classList.contains()
:
只需使用classList.contains()
:
if (document.body.classList.contains('thatClass')) {
// do some stuff
}
Other uses of classList
:
的其他用途classList
:
document.body.classList.add('thisClass');
// $('body').addClass('thisClass');
document.body.classList.remove('thatClass');
// $('body').removeClass('thatClass');
document.body.classList.toggle('anotherClass');
// $('body').toggleClass('anotherClass');
Browser Support:
浏览器支持:
- Chrome 8.0
- Firefox 3.6
- IE 10
- Opera 11.50
- Safari 5.1
- 铬 8.0
- 火狐 3.6
- 浏览器 10
- 歌剧 11.50
- Safari 5.1
回答by raveren
The most effective one liner that
最有效的一种衬垫
- returns a boolean (as opposed to Orbling's answer)
- Does not return a false positive when searching for
thisClass
on an element that hasclass="thisClass-suffix"
. - is compatible with every browser down to at least IE6
- 返回一个布尔值(与 Orbling 的答案相反)
- 在搜索
thisClass
具有class="thisClass-suffix"
. - 与至少 IE6 的所有浏览器兼容
function hasClass( target, className ) {
return new RegExp('(\s|^)' + className + '(\s|$)').test(target.className);
}
回答by StiveAZ
// 1. Use if for see that classes:
if (document.querySelector(".section-name").classList.contains("section-filter")) {
alert("Grid section");
// code...
}
<!--2. Add a class in the .html:-->
<div class="section-name section-filter">...</div>
回答by Orbling
The attribute that stores the classes in use is className
.
存储正在使用的类的属性是className
.
So you can say:
所以你可以说:
if (document.body.className.match(/\bmyclass\b/)) {
....
}
If you want a location that shows you how jQuery does everything, I would suggest:
如果您想要一个显示 jQuery 如何做所有事情的位置,我建议:
回答by Gawin
hasClass function:
hasClass 函数:
HTMLElement.prototype.hasClass = function(cls) {
var i;
var classes = this.className.split(" ");
for(i = 0; i < classes.length; i++) {
if(classes[i] == cls) {
return true;
}
}
return false;
};
addClass function:
添加类函数:
HTMLElement.prototype.addClass = function(add) {
if (!this.hasClass(add)){
this.className = (this.className + " " + add).trim();
}
};
removeClass function:
removeClass 函数:
HTMLElement.prototype.removeClass = function(remove) {
var newClassName = "";
var i;
var classes = this.className.replace(/\s{2,}/g, ' ').split(" ");
for(i = 0; i < classes.length; i++) {
if(classes[i] !== remove) {
newClassName += classes[i] + " ";
}
}
this.className = newClassName.trim();
};
回答by thednp
I use a simple/minimal solution, one line, cross browser, and works with legacy browsers as well:
我使用一个简单/最小的解决方案,一行,跨浏览器,并且也适用于旧版浏览器:
/\bmyClass/.test(document.body.className) // notice the \b command for whole word 'myClass'
This method is great because does not require polyfillsand if you use them for classList
it's much better in terms of performance. At least for me.
这种方法很棒,因为不需要polyfills,如果你使用它们,classList
它的性能会好得多。至少对于我来说。
Update: I made a tiny polyfill that's an all round solution I use now:
更新:我做了一个小小的 polyfill,这是我现在使用的全方位解决方案:
function hasClass(element,testClass){
if ('classList' in element) { return element.classList.contains(testClass);
} else { return new Regexp(testClass).exec(element.className); } // this is better
//} else { return el.className.indexOf(testClass) != -1; } // this is faster but requires indexOf() polyfill
return false;
}
For the other class manipulation, see the complete file here.
对于其他类操作,请参阅此处的完整文件。
回答by Bastian Fie?inger
a good solution for this is to work with classList and contains.
一个很好的解决方案是使用 classList 和 contains。
i did it like this:
我是这样做的:
... for ( var i = 0; i < container.length; i++ ) {
if ( container[i].classList.contains('half_width') ) { ...
So you need your element and check the list of the classes. If one of the classes is the same as the one you search for it will return true if not it will return false!
所以你需要你的元素并检查类列表。如果其中一个类与您搜索的类相同,它将返回 true,否则将返回 false!
回答by Alejandro Nanez
Use something like:
使用类似的东西:
Array.prototype.indexOf.call(myHTMLSelector.classList, 'the-class');
回答by Alexandr Karbivnichiy
if (document.body.className.split(/\s+/).indexOf("thatClass") !== -1) {
// has "thatClass"
}