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

<body class="foo thatClass bar">

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


当前回答

Element.matches ()

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

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

查看浏览器兼容性

其他回答

Element.matches ()

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

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

查看浏览器兼容性

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

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

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

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

/ / 1。使用if来查看这些类: if (document.querySelector(".section-name").classList.contains("section-filter")) { 警报(“网格部分”); / /代码… } < !——2。在.html:——>中添加一个类 <div class="section-name section-filter">

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

我是这样做的:

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

因此,您需要元素并检查类列表。如果其中一个类与你搜索的类相同,它将返回true,如果不是,它将返回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
};