使用纯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类。


当前回答

这有点过时了,但也许有人会发现我的解决方案很有帮助:

// Fix IE's indexOf Array
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement) {
        if (this == null) throw new TypeError();
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) return -1;
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n != n) n = 0;
            else if (n != 0 && n != Infinity && n != -Infinity) n = (n > 0 || -1) * Math.floor(Math.abs(n));
        }
        if (n >= len) return -1;
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) if (k in t && t[k] === searchElement) return k;
        return -1;
    }
}
// add hasClass support
if (!Element.prototype.hasClass) {
    Element.prototype.hasClass = function (classname) {
        if (this == null) throw new TypeError();
        return this.className.split(' ').indexOf(classname) === -1 ? false : true;
    }
}

其他回答

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

使用元素。contains方法:

element.classList.contains(class);

这适用于所有当前的浏览器,也有支持旧浏览器的腻子。


Alternatively, if you work with older browsers and don't want to use polyfills to fix them, using indexOf is correct, but you have to tweak it a little:

function hasClass(element, className) {
    return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1;
}

否则,如果您正在寻找的类是另一个类名的一部分,也会得到true。

DEMO

jQuery使用类似的(如果不是相同的)方法。


应用于本例:

因为这不能和switch语句一起工作,你可以用下面的代码达到同样的效果:

var test = document.getElementById("test"),
    classes = ['class1', 'class2', 'class3', 'class4'];

test.innerHTML = "";

for(var i = 0, j = classes.length; i < j; i++) {
    if(hasClass(test, classes[i])) {
        test.innerHTML = "I have " + classes[i];
        break;
    }
}

它也更少冗余;)

在现代浏览器中,您可以只使用Element的contains方法。班级名册:

testElement.classList.contains(className)

Demo

var testElement = document.getElementById('test'); console.log({ 'main' : testElement.classList.contains('main'), 'cont' : testElement.classList.contains('cont'), 'content' : testElement.classList.contains('content'), 'main-cont' : testElement.classList.contains('main-cont'), 'main-content' : testElement.classList.contains('main-content'), 'main main-content' : testElement.classList.contains('main main-content') }); <div id="test" class="main main-content content"></div>


支持的浏览器

(来自CanIUse.com)


Polyfill

如果你想使用Element。classList,但你也想支持旧的浏览器,考虑使用这个polyfill由Eli Grey。

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.

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

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

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