是否始终定义document.documentElement并始终使用html元素?

sr3*_*sr3 3 html javascript dom

我想<html>从<head>HTML页面元素内的脚本修改元素.我不需要访问/修改任何<html>孩子,只需要<html>自己.

在某些情况下,该脚本是否需要等待DOMContentLoaded或document.documentElement 始终定义?将document.documentElement 始终是<html>元素?

例如:

<html>
  <head>
    <script type="text/javascript">
      document.documentElement.style.foo = 'bar';
    </script>
  </head>
  <body>
    <!-- ... -->
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Pat*_*rts 6

这对于测试非常简单:

<!DOCTYPE html>
<html>
  <head>
    <script>
      console.log(document.documentElement instanceof HTMLHtmlElement);
      console.log(document.documentElement === document.querySelector('html'));
    </script>
  </head>
  <body></body>
</html>
Run Code Online (Sandbox Code Playgroud)

但引用W3C DOM4规范:

[Constructor,
 Exposed=Window]
interface Document : Node {
  ...
  readonly attribute Element? documentElement;
  ...
};
Run Code Online (Sandbox Code Playgroud)

该文档元素一个的文件是元素,其母公司是文件,如果它存在,否则返回null.

注意:根据节点树约束,只能有一个这样的元素.

该规范也在DOM标准中逐字存在.

所以在技术上它是可以为空的,你可以在这里确认一下:

let doc = new Document();
console.log(doc.documentElement);
Run Code Online (Sandbox Code Playgroud)

但是,出于您的目的,当您使用属于它的document那个时<script>,它将永远不会出现null在那种情况下.

  • 它在我的浏览器中进行了简单的测试,但我想确保它在其他浏览器中不会有所不同 - 无论它是否标准化.你的答案的第二部分解决了这个问题.谢谢! (3认同)

Ser*_*yar 4

是的,它总是被定义的。

documentElement 属性以 Element 对象的形式返回文档的 documentElement。对于 HTML 文档,返回的对象是<html>元素。该属性是只读的。

https://www.w3schools.com/jsref/prop_document_documentelement.asp

虽然document.body如果脚本从标签运行<head>并且页面未完全加载,则可以为 null,<html>但元素始终存在于 html 文档中。

  • W3schools [不是](https://meta.stackoverflow.com/q/280478/1541563) 是[权威来源](https://codereview.meta.stackexchange.com/a/4976/73672)。 (3认同)