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

<body class="foo thatClass bar">

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


当前回答

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

其他回答

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

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

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

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

存储正在使用的类的属性是className。

所以你可以说:

if (document.body.className.match(/\bmyclass\b/)) {
    ....
}

如果你想要一个显示jQuery如何做所有事情的位置,我建议:

http://code.jquery.com/jquery-1.5.js

可以使用以下语句:

Array.prototype.indexOf.call(myHTMLSelector.classList, 'the-class');

Element.matches ()

而不是jQuery中的$(element).hasClass('example'),你可以在纯JavaScript中使用element.matches('.example'):

if (element.matches('.example')) {
  // Element has example class ...
}

查看浏览器兼容性

其中最有效的一句话就是

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


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