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


当前回答

查看这个Codepen链接,可以更快更简单地使用JavaScript检查元素是否具有特定的类~!

hasClass (Vanilla JS)

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

其他回答

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

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

我知道有很多答案,但其中大多数是额外的函数和额外的类。这是我个人使用的;更干净,代码行更少!

if( document.body.className.match('category-page') ) { 
  console.log('yes');
}

在哪个元素中当前是类的。酒吧”?这里有另一个解决方案,但取决于你。

var reg = /Image/g, // regexp for an image element
query = document.querySelector('.bar'); // returns [object HTMLImageElement]
query += this.toString(); // turns object into a string

if (query.match(reg)) { // checks if it matches
  alert('the class .bar is attached to the following Element:\n' + query);
}

jsfiddle演示

当然,这只是查找一个简单的元素<img>(/Image/g),但您可以将所有元素放在一个数组中,如<li> is / li /g, <ul> = / ul /g等。

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

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

element.className.includes("class1")