27

How can I check if body has specific class? This is my case:

<body class="foo foo1 foo3"></body>
Wornout
  • 275
  • 1
  • 3
  • 5
  • Have a look at [this question](http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript). It has some great examples. – Martin Hennings Mar 02 '12 at 11:40
  • possible duplicate of [Test if an element contains a class?](http://stackoverflow.com/questions/5898656/test-if-an-element-contains-a-class) -- please use the search before you ask a new question. How it is been done with jQuery [has been ask before as well](http://stackoverflow.com/questions/263232/determine-if-an-element-has-a-css-class-with-jquery). – Felix Kling Mar 02 '12 at 12:05

7 Answers7

86

There's now a super-easy way to do this:

document.body.classList.contains('my-class-name')
gradosevic
  • 4,809
  • 2
  • 36
  • 51
14
document.getElementsByTagName("body")[0].className.match(/foo/)
Luke
  • 11,426
  • 43
  • 60
  • 69
Esben Skov Pedersen
  • 4,437
  • 2
  • 32
  • 46
10

jQuery.hasClass works for me...

non jQuery answer, try if( document.body.className.match('foo') ) { ... }

marko
  • 1,721
  • 15
  • 25
9
function hasClass(ele,cls) {
     return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

if(hasClass(document.getElementById("test"), "test")){//do something};

maybe this helps you :-)

With the use of jQuery it would be easier and less code but nevermind !

mas-designs
  • 7,498
  • 1
  • 31
  • 56
1

This returns a string of true or false when looking for a specific body class using jQuery's .hasClass:

if ($("body").hasClass("modal-open")) {
                        $("body").removeClass("modal-open");
                    }
Rajendran S
  • 39
  • 1
  • 12
1

You can use the Mozilla classList for this.

The linked page also has a cross-browser solution.

Martin Hennings
  • 16,418
  • 9
  • 48
  • 68
0

This returns a string of true or false when looking for a specific body class using jQuery's .hasClass:

$("body").hasClass("your-class-name").toString();
serraosays
  • 7,163
  • 3
  • 35
  • 60