7
votes

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.

2
code is running before body is loadingPranav C Balan
Yeah, I know. That's what the error means.crowhill

2 Answers

9
votes

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>
1
votes

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.