![](/img/trans.png)
[英]Is there anything wrong with adding an HTML element as a direct child of document.documentElement?
[英]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.