如何做jQuery的hasClass与平原ol ' JavaScript?例如,

<body class="foo thatClass bar">

JavaScript中询问<body>是否有thatClass的方法是什么?


当前回答

我使用一个简单/最小的解决方案,一行,跨浏览器,并与传统浏览器一起工作:

/\bmyClass/.test(document.body.className) // notice the \b command for whole word 'myClass'

这个方法很好,因为不需要填充,如果你把它们用于classList,它在性能方面要好得多。至少对我来说是这样。

更新:我做了一个小的填充,这是一个全方位的解决方案,我现在使用:

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;
}

有关其他类操作,请参阅此处的完整文件。

其他回答

这个'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
};

其中最有效的一句话就是

返回一个布尔值(与Orbling的答案相反) 在具有class="thisClass-suffix"的元素上搜索thisClass时,不会返回假阳性。 能兼容IE6以下的所有浏览器吗


function hasClass( target, className ) {
    return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
}

您可以检查元素是否。className匹配/\bthatClass\b/。 \b匹配一个换行符。

或者,你可以使用jQuery自己的实现:

var className = " " + selector + " ";
if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" thatClass ") > -1 ) 

要回答你更普遍的问题,你可以在github上查看jQuery的源代码,或者在这个源代码查看器中查看hasClass的源代码。

一个很好的解决方案是使用classList和contains。

我是这样做的:

... for ( var i = 0; i < container.length; i++ ) {
        if ( container[i].classList.contains('half_width') ) { ...

因此,您需要元素并检查类列表。如果其中一个类与你搜索的类相同,它将返回true,如果不是,它将返回false!

if (document.body.className.split(/\s+/).indexOf("thatClass") !== -1) {
    // has "thatClass"
}