使用纯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类。
要检查元素是否包含类,可以使用元素classList属性的contains()方法:*
element.classList.contains(className);
*假设你有以下元素:
<div class="secondary info">Item</div>*
要检查元素是否包含二级类,可以使用以下代码:
const div = document.querySelector('div');
div.classList.contains('secondary'); // true
下面返回false,因为元素没有类错误:
const div = document.querySelector('div');
div.classList.contains('error'); // false
这有点过分,但是如果你有一个触发switch的事件,你可以不使用类:
<div id="classOne1"></div>
<div id="classOne2"></div>
<div id="classTwo3"></div>
你可以这样做
$('body').click( function() {
switch ( this.id.replace(/[0-9]/g, '') ) {
case 'classOne': this.innerHTML = "I have classOne"; break;
case 'classTwo': this.innerHTML = "I have classTwo"; break;
default: this.innerHTML = "";
}
});
.replace(/[0-9]/g, ")删除id中的数字。
这有点俗气,但适用于没有额外函数或循环的长开关
这里有一个小片段,如果你试图检查元素是否包含一个类,而不使用jQuery。
function hasClass(element, className) {
return element.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(element.className);
}
这说明元素可能包含多个用空格分隔的类名。
OR
您还可以将此函数分配给元素原型。
Element.prototype.hasClass = function(className) {
return this.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(this.className);
};
并像这样触发它(非常类似于jQuery的.hasClass()函数):
document.getElementById('MyDiv').hasClass('active');
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.