Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using vanilla javascript, add class to body from within head

Tags:

javascript

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.

like image 502
crowhill Avatar asked Jan 25 '17 07:01

crowhill


People also ask

Can I add class to the body element?

We used the add() method to add a class on the body object. We can access the body element on the document object. If the class is already present on the body element, it won't get added twice. You can pass as many classes to the add() method as necessary.

How do I add a class to my body in TypeScript?

To add a class to the body element in TypeScript, call the classList. add() method on the body object, e.g. document.


2 Answers

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>
like image 96
Pranav C Balan Avatar answered Nov 15 '22 15:11

Pranav C Balan


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.

like image 37
Horia Coman Avatar answered Nov 15 '22 16:11

Horia Coman