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>
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>
Share
Improve this question
asked Nov 1, 2017 at 7:11
sr3sr3
3992 gold badges5 silver badges17 bronze badges
2 Answers
Reset to default 9This 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.
Yes, it's always defined.
The documentElement property returns the documentElement of the document, as an Element object. For HTML documents the returned object is the
<html>
element. This property is read-only.
https://www.w3schools./jsref/prop_document_documentelement.asp
While document.body
can be null if script is running from <head>
tag and page is not fully loaded, <html>
element is always present in html document.