Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is document.documentElement always defined and always the html element?

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>
like image 810
sr3 Avatar asked Dec 18 '22 03:12

sr3


1 Answers

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.

like image 97
Patrick Roberts Avatar answered Mar 01 '23 22:03

Patrick Roberts