javascript 检查没有 jQuery 的 CSS 类是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8405413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a CSS class exists without jQuery
提问by Zac
Using vanilla javascript or prototype can someone show me how I could run a check to see if a class exists? For example I am adding a class called hideIt with this code :
有人可以使用 vanilla javascript 或原型向我展示如何运行检查以查看类是否存在?例如,我正在使用以下代码添加一个名为 hideIt 的类:
var overlay = document.getElementById("overlay_modal");
overlay.className += " hideIt";
I also need a script that later can check to see if hideIt exists. I have tried things like :
我还需要一个脚本,稍后可以检查是否存在 hideIt。我试过这样的事情:
if (overlay.className == "hideIt")
But that is no good. Any ideas?
但这不好。有任何想法吗?
采纳答案by Matt Ball
回答by David says reinstate Monica
You could use getElementsByClassName()
, albeit this isn't supported in allbrowsers (not in IE < 9):
您可以使用getElementsByClassName()
,尽管并非所有浏览器都支持此功能(IE < 9 除外):
if (!document.getElementsByClassName('classname').length){
// class name does not exist in the document
}
else {
// class exists in the document
}
You could, depending on browser compatibility requirements, use querySelectorAll()
:
根据浏览器兼容性要求,您可以使用querySelectorAll()
:
if (document.querySelectorAll('#overlay_modal.hideIt')) {
// the element with id of overlay_modal exists and has the class-name 'hideIt'
}
References:
参考:
回答by Mike
var id = document.getElementById("id");
var classes = id.className.split(" ");
if(classes.indexOf("class_name") == -1)
{
}
回答by clockworkgeek
Because the question asks for it here also is the Prototype way,
因为这里问的问题也是Prototype方式,
if (overlay.hasClassName('hideIt'))