最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is document.documentElement always defined and always the html element? - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 9

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.

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.

发布评论

评论列表(0)

  1. 暂无评论