Test if an element contains a class?

2018-12-31 19:40发布

Using plain JavaScript (not jQuery), is there a way I can test to see if an element contains a class?

Currently, I'm doing this:

HTML:

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

JS:

var test = document.getElementById("test");
var testClass = test.className;
switch(testClass){
    case "class1": test.innerHTML = "I have class1"; break;
    case "class2": test.innerHTML = "I have class2"; break;
    case "class3": test.innerHTML = "I have class3"; break;
    case "class4": test.innerHTML = "I have class4"; break;
    default: test.innerHTML = "";
}

This results in this output, which is correct:

I have class1

The issue is that if I change the HTML to this...

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

...there's no longer an exact match, so I get the default output of nothing (""). But I still want the output to be I have class1 because the <div> still contains the .class1 class.

23条回答
无与为乐者.
2楼-- · 2018-12-31 20:14

Since he wants to use switch(), I'm surprised no one has put this forth yet:

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/>";
    }
}
查看更多
明月照影归
3楼-- · 2018-12-31 20:14

Try this one:

document.getElementsByClassName = function(cl) {
   var retnode = [];
   var myclass = new RegExp('\\b'+cl+'\\b');
   var elem = this.getElementsByTagName('*');
   for (var i = 0; i < elem.length; i++) {
       var classes = elem[i].className;
       if (myclass.test(classes)) retnode.push(elem[i]);
   }
    return retnode;
};
查看更多
只若初见
4楼-- · 2018-12-31 20:16

Here is a little snippet If you’re trying to check wether element contains a class, without using jQuery.

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

This accounts for the fact that element might contain multiple class names separated by space.

OR


You can also assign this function to element prototype.

Element.prototype.hasClass = function(className) {
    return this.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(this.className);
};

And trigger it like this (very similar to jQuery’s .hasClass() function):

document.getElementById('MyDiv').hasClass('active');
查看更多
梦该遗忘
5楼-- · 2018-12-31 20:16

I know there a lot of answers but most of these are for additional functions and additional classes. This is the one I personally use; much cleaner and much less lines of code!

if( document.body.className.match('category-page') ) { 
  console.log('yes');
}
查看更多
梦该遗忘
6楼-- · 2018-12-31 20:17

See this Codepen link for faster and easy way of checking an element if it has a specific class using vanilla JavaScript~!

hasClass (Vanilla JS)

function hasClass(element, cls) {
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
查看更多
荒废的爱情
7楼-- · 2018-12-31 20:19

Here's a case-insensitive trivial solution:

function hasClass(element, classNameToTestFor) {
    var classNames = element.className.split(' ');
    for (var i = 0; i < classNames.length; i++) {
        if (classNames[i].toLowerCase() == classNameToTestFor.toLowerCase()) {
            return true;
        }
    }
    return false;
}
查看更多
登录 后发表回答