简体   繁体   English

检查是否存在没有jQuery的CSS类

[英]Check if a CSS class exists without jQuery

Using vanilla javascript or prototype can someone show me how I could run a check to see if a class exists? 使用vanilla javascript或原型可以有人告诉我如何运行检查以查看是否存在类? For example I am adding a class called hideIt with this code : 例如,我正在使用以下代码添加一个名为hideIt的类:

var overlay = document.getElementById("overlay_modal");
overlay.className += " hideIt";

I also need a script that later can check to see if hideIt exists. 我还需要一个脚本,以后可以检查hideIt是否存在。 I have tried things like : 我尝试过这样的事情:

if (overlay.className == "hideIt")

But that is no good. 但那并不好。 Any ideas? 有任何想法吗?

Use a regexp . 使用正则表达式 \\b will 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
}

You could use getElementsByClassName() , albeit this isn't supported in all browsers (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: 参考文献:

var id = document.getElementById("id");
var classes = id.className.split(" ");
if(classes.indexOf("class_name") == -1)
{
}

Because the question asks for it here also is the Prototype way , 因为这里问的问题也是原型方式

if (overlay.hasClassName('hideIt'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM