How check if body has a specific class with JavaScript?

最后都变了- 提交于 2020-01-10 23:02:33

问题


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

<body class="foo foo1 foo3"></body>

回答1:


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 !




回答2:


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

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



回答3:


document.getElementsByTagName("body")[0].className.match(/foo/)



回答4:


jQuery.hasClass works for me...

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




回答5:


You can use the Mozilla classList for this.

The linked page also has a cross-browser solution.




回答6:


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



回答7:


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");
                    }


来源:https://stackoverflow.com/questions/9532639/how-check-if-body-has-a-specific-class-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!