admin管理员组文章数量:1415062
I have a body element on which I add a few classes. And I want to remove the no-javascript
class from it, after it's being read by the browser.
<body class="foo boo no-javascript bla">
<script type="javascript">
// remove no-javascript class here
</script>
I have a body element on which I add a few classes. And I want to remove the no-javascript
class from it, after it's being read by the browser.
<body class="foo boo no-javascript bla">
<script type="javascript">
// remove no-javascript class here
</script>
Share
Improve this question
edited May 14, 2015 at 10:32
Stephan Muller
27.6k17 gold badges86 silver badges127 bronze badges
asked Dec 9, 2010 at 10:39
AlexAlex
68.3k184 gold badges459 silver badges650 bronze badges
5 Answers
Reset to default 60Well, since extra spaces between don't matter, I'd say:
document.body.className = document.body.className.replace("no-javascript","");
You can test it out here.
document.querySelector('body').classList.remove('no-javascript');
There are no native javascript functions for this, but I always use the following code (borrowed from/inspired by this snipplr
function removeClass(ele,cls) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className = ele.className.replace(reg,' ');
}
removeClass(document.getElementById("body"), "no-javascript")
The regex does a better job than the replace
functions mentioned in other answers, because it checks for the existence of that exact className and nothing more or less. A class named "piano-javascript" would stay intact with this version.
For modern browsers (including IE10 and up) you could also use:
document.querySelector('body').classList.remove('no-javascript');
document.body.className = '';
You can avoid all of that work simply by using
<noscript>Your browser does not support JavaScript!</noscript>
Since whatever you put inside of noscript
tag will be shown if Javascript is turned off and nothing will be shown if JS is turned on.
本文标签: htmlJavascriptfastest way to remove a class from ltbodygtStack Overflow
版权声明:本文标题:html - Javascript, fastest way to remove a class from `<body>` - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737094575a1962668.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论