检查一个元素是否包含 JavaScript 中的类?
2022-08-29 22:25:13
使用普通的JavaScript(不是jQuery),有没有办法检查一个元素是否包含类?
目前,我正在这样做:
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 = "";
}
<div id="test" class="class1"></div>
问题是,如果我将HTML更改为此...
<div id="test" class="class1 class5"></div>
...不再有完全匹配,因此我得到无的默认输出()。但我仍然希望输出是,因为静止包含类。""
I have class1
<div>
.class1