-2

I am trying to simply show/hide content; by creating an if statement in plain JS to detect if the current body tag has a specific class attached; i.e. home

I am trying the below; on the correct page, but am not getting the alert.

var elem = document.querySelector('body');

if (elem.classList.contains('test')) {
    alert('test');
}

no jQuery!!

error with the above code is:

Uncaught TypeError: Cannot read property 'classList' of null

I just want this to run on page load

Dr Upvote
  • 8,023
  • 24
  • 91
  • 204

1 Answers1

0

As long as you wait for the DOMContentLoaded event you should be golden. Check out the tests below.

NOTE: Snippet engine is NOT a good test for this, the HTML is always ready :)

document.addEventListener('DOMContentLoaded', () => {
  console.log(document.body.classList);
  console.log(document.body.className);
  if(document.body.classList.length > 0) {
    console.log(document.body.className);
  }

});
<body class="testing test2">

<p>Hello world</p>

</body>
Bibberty
  • 4,670
  • 2
  • 8
  • 23