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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:20:46  来源:igfitidea点击:

Check if a CSS class exists without jQuery

javascriptprototypejs

提问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

Use a regexp. \bwill match word boundaries (a space, a newline character, punctuation character or end of string).

使用正则表达式\b将匹配单词边界(空格、换行符、标点字符或字符串结尾)。

var overlay = document.getElementById("overlay_modal");
if (overlay.className.match(/\bhideIt\b/)) 
{
    // frob a widget
}

回答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'))