Javascript, fastest way to remove a class from `<body>`

后端 未结 5 880
不知归路
不知归路 2021-01-31 09:44

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.

           


        
相关标签:
5条回答
  • 2021-01-31 10:25

    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.

    0 讨论(0)
  • 2021-01-31 10:26
    document.querySelector('body').classList.remove('no-javascript');
    
    0 讨论(0)
  • 2021-01-31 10:42

    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');
    
    0 讨论(0)
  • 2021-01-31 10:43
    document.body.className = '';
    
    0 讨论(0)
  • 2021-01-31 10:49

    Well, 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.

    0 讨论(0)
提交回复
热议问题