[英]Check if a CSS class exists without jQuery
使用vanilla javascript或原型可以有人告诉我如何运行检查以查看是否存在类? 例如,我正在使用以下代码添加一个名为hideIt的类:
var overlay = document.getElementById("overlay_modal");
overlay.className += " hideIt";
我还需要一个脚本,以后可以检查hideIt是否存在。 我尝试过这样的事情:
if (overlay.className == "hideIt")
但那并不好。 有任何想法吗?
使用正则表达式 。 \\b
将匹配单词边界(空格,换行符,标点符号或字符串结尾)。
var overlay = document.getElementById("overlay_modal");
if (overlay.className.match(/\bhideIt\b/))
{
// frob a widget
}
您可以使用getElementsByClassName()
,虽然并非所有浏览器都支持(不在IE <9中):
if (!document.getElementsByClassName('classname').length){
// class name does not exist in the document
}
else {
// class exists in the document
}
根据浏览器兼容性要求,您可以使用querySelectorAll()
:
if (document.querySelectorAll('#overlay_modal.hideIt')) {
// the element with id of overlay_modal exists and has the class-name 'hideIt'
}
参考文献:
var id = document.getElementById("id");
var classes = id.className.split(" ");
if(classes.indexOf("class_name") == -1)
{
}
因为这里问的问题也是原型方式 ,
if (overlay.hasClassName('hideIt'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.