I'd like to modify the <html>
element from a script that's inside the <head>
element of an HTML page. I don't need to access/modify any of <html>
's children, just <html>
itself.
Would that script in some cases need to wait for DOMContentLoaded
, or will document.documentElement
always be defined? Will document.documentElement
always be the <html>
element?
For example:
<html>
<head>
<script type="text/javascript">
document.documentElement.style.foo = 'bar';
</script>
</head>
<body>
<!-- ... -->
</body>
</html>
This is quite trivial to test:
<!DOCTYPE html>
<html>
<head>
<script>
console.log(document.documentElement instanceof HTMLHtmlElement);
console.log(document.documentElement === document.querySelector('html'));
</script>
</head>
<body></body>
</html>
But to quote the W3C DOM4 specification:
[Constructor, Exposed=Window] interface Document : Node { ... readonly attribute Element? documentElement; ... };
The document element of a document is the element whose parent is that document, if it exists, and null otherwise.
Note: Per the node tree constraints, there can only be one such element.
This specification exists verbatim in the DOM Standard as well.
So technically it is nullable, as you can confirm here:
let doc = new Document();
console.log(doc.documentElement);
However, for your purposes, as you're using the document
that a <script>
belongs to, it will never be null
in that case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With