3 ms·
That's just because of ordering, though. Test it: <html> <body></body> <head><script>alert(document.body);</script></head> </html> works f
by Jasper_ 10y ago
That's just because of ordering, though. Test it:
<html>
<body></body>
<head><script>alert(document.body);</script></head>
</html>
works fine. It's not a head vs. body distinction, it's just that the parser is stopped during inline scripts, and doing e.g. getElementById won't work if the script is declared after you.
This is why window.onload and then jQuery's document.ready, and later, putting the script at the end of your file, is a best practice.
- Sidnicious 10y agoWhat's happening isn't what you think is happening. The parser creates an empty head element when it sees the <body> start tag, the second <head> start tag is ignored, and the <script> is treated as part of the body element. Try changing the body of the <script> tag to this: alert(document.currentScript.parentNode); It alerts "[object HTMLBodyElement]". The behavior is specced out here, if you're curious: https://www.w3.org/TR/html5/syntax.html#parsing-main-afterbody https://www.w3.org/TR/html5/syntax.html#parsing-main-afterbo...