繁体   English   中英

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

[英]Is document.documentElement always defined and always the html element?

我想修改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>

这对于测试非常简单:

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

但引用W3C DOM4规范

 [Constructor, Exposed=Window] interface Document : Node { ... readonly attribute Element? documentElement; ... }; 

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

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

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

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

 let doc = new Document(); console.log(doc.documentElement); 

但是,出于您的目的 ,当您使用<script>所属的document ,在这种情况下它永远不会为null

是的,它始终是定义的。

documentElement属性返回文档的documentElement,作为Element对象。 对于HTML文档,返回的对象是<html>元素。 此属性是只读的。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM