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

<body class="foo thatClass bar">

JavaScript中询问<body>是否有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 ...
}

查看浏览器兼容性

其中最有效的一句话就是

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


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

只需使用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

浏览器支持

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

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

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

你对这种方法有什么看法?

<body class="thatClass anotherClass"> </body>

var bodyClasses = document.querySelector('body').className;
var myClass = new RegExp("thatClass");
var trueOrFalse = myClass.test( bodyClasses );

https://jsfiddle.net/5sv30bhe/