如果元素有多个类,那么它将与常规属性值检查不匹配,所以我正在寻找检查对象是否在元素的className属性中具有特定类的最佳方法.
// element's classname is 'hello world helloworld'
var element = document.getElementById('element');
// this obviously fails
if(element.className == 'hello'){ ... }
// this is not good if the className is just 'helloworld' because it will match
if(element.className.indexOf('hello') != -1){ ... }
Run Code Online (Sandbox Code Playgroud)
那么最好的方法是什么?
只是纯粹的JavaScript请
Esa*_*ija 38
function hasClass( elem, klass ) {
return (" " + elem.className + " " ).indexOf( " "+klass+" " ) > -1;
}
Run Code Online (Sandbox Code Playgroud)
ZER*_*ER0 26
在现代浏览器中,您可以使用classList:
if (element.classList.contains("hello")) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
在没有实现classList但暴露DOM原型的浏览器中,您可以使用链接中显示的填充程序.
否则,您可以使用相同的垫片代码来获得通用函数,而无需操作原型.
| 归档时间: |
|
| 查看次数: |
38209 次 |
| 最近记录: |