使用纯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是一个字符串,你可以使用string includes()方法来检查你的.className是否包含你的类名:

element.className.includes("class1")

其他回答

对我来说,最优雅、最快速的实现方法是:

function hasClass(el, cl) {
        return el.classList ? el.classList.contains(cl) : !!el.className && !!el.className.match(new RegExp('(?: |^)' + cl + '(?: |$)'));
    }

className只是一个字符串,所以您可以使用常规的indexOf函数来查看类列表是否包含另一个字符串。

我将保利填充classList功能,并使用新的语法。这样,新的浏览器将使用新的实现(速度快得多),只有旧的浏览器会受到代码的性能影响。

https://github.com/remy/polyfills/blob/master/classList.js

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(名称);

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.