如何做jQuery的hasClass与平原ol ' JavaScript?例如,
<body class="foo thatClass bar">
JavaScript中询问<body>是否有thatClass的方法是什么?
如何做jQuery的hasClass与平原ol ' JavaScript?例如,
<body class="foo thatClass bar">
JavaScript中询问<body>是否有thatClass的方法是什么?
当前回答
if (document.body.className.split(/\s+/).indexOf("thatClass") !== -1) {
// has "thatClass"
}
其他回答
其中最有效的一句话就是
返回一个布尔值(与Orbling的答案相反) 在具有class="thisClass-suffix"的元素上搜索thisClass时,不会返回假阳性。 能兼容IE6以下的所有浏览器吗
function hasClass( target, className ) {
return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
}
这个'hasClass'函数适用于IE8+, FireFox和Chrome:
hasClass = function(el, cls) {
var regexp = new RegExp('(\\s|^)' + cls + '(\\s|$)'),
target = (typeof el.className === 'undefined') ? window.event.srcElement : el;
return target.className.match(regexp);
}
[更新于2021年1月]更好的方法:
hasClass = (el, cls) => {
[...el.classList].includes(cls); //cls without dot
};
if (document.body.className.split(/\s+/).indexOf("thatClass") !== -1) {
// has "thatClass"
}
存储正在使用的类的属性是className。
所以你可以说:
if (document.body.className.match(/\bmyclass\b/)) {
....
}
如果你想要一个显示jQuery如何做所有事情的位置,我建议:
http://code.jquery.com/jquery-1.5.js
Element.matches ()
而不是jQuery中的$(element).hasClass('example'),你可以在纯JavaScript中使用element.matches('.example'):
if (element.matches('.example')) {
// Element has example class ...
}
查看浏览器兼容性