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

<body class="foo thatClass bar">

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


当前回答

好吧,上面所有的答案都很好,但这里有一个简单的小函数。它运行得很好。

function hasClass(el, cn){
    var classes = el.classList;
    for(var j = 0; j < classes.length; j++){
        if(classes[j] == cn){
            return true;
        }
    }
}

其他回答

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

我是这样做的:

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

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

只需使用classList.contains():

if (document.body.classList.contains('thatClass')) {
    // do some stuff
}

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');

浏览器支持:

Chrome 8.0 Firefox 3.6 IE 10 Opera 11.50 Safari 5.1

浏览器支持

Element.matches ()

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

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

查看浏览器兼容性

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

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