How to check if a body has a specific class with JavaScript?

How to check if a body has a certain class? This is my case:

<body class="foo foo1 foo3"></body> 
+4
source share
6 answers
 function hasClass(ele,cls) { return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } if(hasClass(document.getElementById("test"), "test")){//do something}; 

maybe this will help you :-)

Using jQuery would be simpler and less code, but never mind!

+5
source
 document.getElementsByTagName("body")[0].className.match(/foo/) 
+11
source

jQuery.hasClass works for me ...

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

+8
source

There is currently a very simple way to do this:

 document.body.classList.contains('my-class-name') 
+6
source

You can use the Mozilla class list for this.

The linked page also has a cross-browser solution.

+1
source

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

 $("body").hasClass("your-class-name").toString(); 
0
source

Source: https://habr.com/ru/post/1399375/


All Articles