最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if a CSS class exists without jQuery - Stack Overflow

programmeradmin4浏览0评论

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 :

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 :

if (overlay.className == "hideIt")

But that is no good. Any ideas?

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 :

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 :

if (overlay.className == "hideIt")

But that is no good. Any ideas?

Share Improve this question edited Dec 27, 2011 at 14:16 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Dec 6, 2011 at 19:12 ZacZac 12.8k21 gold badges76 silver badges124 bronze badges 0
Add a comment  | 

4 Answers 4

Reset to default 6

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

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):

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():

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

References:

  • Compatibility for querySelectorAll at Quirksmode.
  • querySelectorAll() at Mozilla Developer Network.
  • getElementsByClassName() at Mozilla Developer Network.
  • Compatibility for getElementsByClassName(), at Quirksmode.
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'))
发布评论

评论列表(0)

  1. 暂无评论