使用纯JavaScript(不是jQuery),是否有任何方法来检查元素是否包含类?

目前,我正在这样做:

var test = document.getElementById("test"); var testClass = test.className; switch (testClass) { 例“class1”: 测试。innerHTML = "我有class1"; 打破; 例“class2”: 测试。innerHTML = "I have class2"; 打破; 例“class3”: 测试。innerHTML = "I have class3"; 打破; “一年级”情况: 测试。innerHTML = "I have class4"; 打破; 默认值: 测试。innerHTML = ""; } <div id="test" class="class1"></div>

问题是,如果我把HTML改成这个…

<div id="test" class="class1 class5"></div>

...不再有一个精确的匹配,所以我得到的默认输出为nothing("")。但我仍然希望输出为I have class1,因为<div>仍然包含。class1类。


当前回答

正如公认的答案所示,元素。className返回一个字符串,所以你可以通过使用indexOf()方法轻松检查类是否存在:

element.className.indexOf('animated') > -1

如果你对indexOf和classList之间的性能差异感兴趣。contains,使用indexOf似乎稍微快一些。我做了一个快速的基准性能测试来验证这一点。以下是我的发现:indexOf vs ClassList.contains。

其他回答

Felix's trick of adding spaces to flank the className and the string you're searching for is the right approach to determining whether the elements has the class or not. To have different behaviour according to the class, you may use function references, or functions, within a map: function fn1(element){ /* code for element with class1 */ } function fn2(element){ /* code for element with class2 */ } function fn2(element){ /* code for element with class3 */ } var fns={'class1': fn1, 'class2': fn2, 'class3': fn3}; for(var i in fns) { if(hasClass(test, i)) { fns[i](test); } } for(var i in fns) iterates through the keys within the fns map. Having no break after fnsi allows the code to be executed whenever there is a match - so that if the element has, f.i., class1 and class2, both fn1 and fn2 will be executed. The advantage of this approach is that the code to execute for each class is arbitrary, like the one in the switch statement; in your example all the cases performed a similar operation, but tomorrow you may need to do different things for each. You may simulate the default case by having a status variable telling whether a match was found in the loop or not.

因为他想使用switch(),我很惊讶没有人提出这个:

var test = document.getElementById("test");
var testClasses = test.className.split(" ");
test.innerHTML = "";
for(var i=0; i<testClasses.length; i++) {
    switch(testClasses[i]) {
        case "class1": test.innerHTML += "I have class1<br/>"; break;
        case "class2": test.innerHTML += "I have class2<br/>"; break;
        case "class3": test.innerHTML += "I have class3<br/>"; break;
        case "class4": test.innerHTML += "I have class4<br/>"; break;
        default: test.innerHTML += "(unknown class:" + testClasses[i] + ")<br/>";
    }
}

因为.className是一个字符串,你可以使用string includes()方法来检查你的.className是否包含你的类名:

element.className.includes("class1")

我已经创建了一个使用classList的原型方法,如果可能,否则诉诸indexOf:

Element.prototype.hasClass = Element.prototype.hasClass || function(classArr){ var hasClass = 0, className = this.getAttribute('class'); if( this == null || !classArr || !className ) return false; if( !(classArr instanceof Array) ) classArr = classArr.split(' '); for( var i in classArr ) // this.classList.contains(classArr[i]) // for modern browsers if( className.split(classArr[i]).length > 1 ) hasClass++; return hasClass == classArr.length; }; /////////////////////////////// // TESTS (see browser's console when inspecting the output) var elm1 = document.querySelector('p'); var elm2 = document.querySelector('b'); var elm3 = elm1.firstChild; // textNode var elm4 = document.querySelector('text'); // SVG text console.log( elm1, ' has class "a": ', elm1.hasClass('a') ); console.log( elm1, ' has class "b": ', elm1.hasClass('b') ); console.log( elm1, ' has class "c": ', elm1.hasClass('c') ); console.log( elm1, ' has class "d": ', elm1.hasClass('d') ); console.log( elm1, ' has class "a c": ', elm1.hasClass('a c') ); console.log( elm1, ' has class "a d": ', elm1.hasClass('a d') ); console.log( elm1, ' has class "": ', elm1.hasClass('') ); console.log( elm2, ' has class "a": ', elm2.hasClass('a') ); // console.log( elm3, ' has class "a": ', elm3.hasClass('a') ); console.log( elm4, ' has class "a": ', elm4.hasClass('a') ); <p class='a b c'>This is a <b>test</b> string</p> <svg xmlns="http://www.w3.org/2000/svg" width="100px" height="50px"> <text x="10" y="20" class='a'>SVG Text Example</text> </svg>

测试页面

IE8+支持。

首先,我们检查classList是否存在,如果存在,我们可以使用IE10+支持的contains方法。如果我们是在IE9或ie8上,它就会退回到使用正则表达式,它没有那么高效,但是一个简洁的填充。

if (el.classList) {
  el.classList.contains(className);
} else {
  new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
}

或者,如果你正在使用babel编译,你可以简单地使用: el.classList.contains(名称);