0
<html>
<head>
<script>alert(document.body.className);</script>
</head>
<body>
something
</body>
</html>

I hope this code may return a classname of the body.

But instead, I get Uncaught TypeError: Cannot read property 'className' of null

Is there some way to get and set classname of the body in head before domready event?

The only way is to append this code to domready event?

John Rake
  • 13
  • 3
  • ...Your javascript isn't even wrapped in `` tags...how is that even executing? – crush Jan 24 '13 at 13:06
  • in fact it's wrapped, forgot to add this to an example. – John Rake Jan 24 '13 at 13:07
  • 1
    When the `` is being processed, and the JavaScript being executed, the `` tag hasn't been reached yet so it won't know what the class is supposed to be. – Anthony Grist Jan 24 '13 at 13:07
  • Documents are loaded from the top down, so if your Javascript runs before the body tag has been processed, then it won't know that Body exists. You can either place your code inside of the body tag, or you can hook the dom ready event. – crush Jan 24 '13 at 13:08
  • the nearest event to get body's class is domready? – John Rake Jan 24 '13 at 13:08
  • @JohnRezza If you want to keep the ` – Anthony Grist Jan 24 '13 at 13:10

1 Answers1

0

Not with JavaScript. You can't access document.body until the body element exists. It does not exist until virtually the entire page is rendered (because the closing is the second last tag on any page)

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100