简体   繁体   中英

Using vanilla javascript, add class to body from within head

I want to do a quick javascript check from within the head tag, like so:

<html>
    <head>
        ...
        <script>
            document.body.classList.remove("no-js");
            document.body.classList.add("js");
        </script>
    </head>
    <body class='no-js'>
        ...
    </body>
</html>

This doesn't work. Cannot read property classList of null , which...fair enough. If I move the <script> tag into <body> , everything works, but I want the <script> tag in <head> .

What are my options?

EDIT: I should have been much clearer about the error. I realize the problem is that body hasn't loaded when I'm trying to to add the class. However, I was using a bit of Modernizr originally and it was somehow able to modify the body class from within the head and I don't think it was using window.onload or anything like that.

Run the code after body is loaded. There are several approaches to solve the problem:

  1. Move the code into a named function defined in global context and call it in onload .

 <html> <head> ... <script> function load() { document.body.classList.remove("no-js"); document.body.classList.add("js"); } </script> </head> <body onload="load();" class='no-js'> ... </body> </html>

  1. Or move code to DOMContentLoaded event listener callback in order to call after dom elements are loaded.

 <html> <head> ... <script> document.addEventListener("DOMContentLoaded", function() { document.body.classList.remove("no-js"); document.body.classList.add("js"); }); </script> </head> <body class='no-js'> ... </body> </html>

  1. Or move the entire script tag to the end of the page.

 <html> <head> ... </head> <body class='no-js'> ... <script> document.body.classList.remove("no-js"); document.body.classList.add("js"); </script> </body> </html>

At the time the javascript is executed there is no body tag, because the browser hasn't gotten around to it yet. You need to either add the script tag in the body, or add it as an event to execute when the document has loaded. See DOMContentLoaded for an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM