How check if body has a specific class with JavaScript?

后端 未结 7 1854
不思量自难忘°
不思量自难忘° 2021-01-01 16:40

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


相关标签:
7条回答
  • 2021-01-01 17:02

    You can use the Mozilla classList for this.

    The linked page also has a cross-browser solution.

    0 讨论(0)
  • 2021-01-01 17:11

    jQuery.hasClass works for me...

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

    0 讨论(0)
  • 2021-01-01 17:15
    document.getElementsByTagName("body")[0].className.match(/foo/)
    
    0 讨论(0)
  • 2021-01-01 17:16

    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();
    
    0 讨论(0)
  • 2021-01-01 17:19
    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 !

    0 讨论(0)
  • 2021-01-01 17:19

    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");
                        }
    
    0 讨论(0)
提交回复
热议问题