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

Zac*_*Zac 6 javascript prototypejs

使用vanilla javascript或原型可以有人告诉我如何运行检查以查看是否存在类?例如,我正在使用以下代码添加一个名为hideIt的类:

var overlay = document.getElementById("overlay_modal");
overlay.className += " hideIt";
Run Code Online (Sandbox Code Playgroud)

我还需要一个脚本,以后可以检查hideIt是否存在.我尝试过这样的事情:

if (overlay.className == "hideIt")
Run Code Online (Sandbox Code Playgroud)

但那并不好.有任何想法吗?

Mat*_*all 6

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

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


Dav*_*mas 5

您可以使用getElementsByClassName(),尽管并非所有浏览器支持此功能(不在 IE < 9 中):

if (!document.getElementsByClassName('classname').length){
    // class name does not exist in the document
}

else {
    // class exists in the document
}
Run Code Online (Sandbox Code Playgroud)

根据浏览器兼容性要求,您可以使用querySelectorAll()

if (document.querySelectorAll('#overlay_modal.hideIt')) {
    // the element with id of overlay_modal exists and has the class-name 'hideIt'
}
Run Code Online (Sandbox Code Playgroud)

参考: