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)
这对于测试非常简单:
<!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规范:
Run Code Online (Sandbox Code Playgroud)[Constructor, Exposed=Window] interface Document : Node { ... readonly attribute Element? documentElement; ... };该文档元素一个的文件是元素,其母公司是文件,如果它存在,否则返回null.
该规范也在DOM标准中逐字存在.
所以在技术上它是可以为空的,你可以在这里确认一下:
let doc = new Document();
console.log(doc.documentElement);Run Code Online (Sandbox Code Playgroud)
但是,出于您的目的,当您使用属于它的document那个时<script>,它将永远不会出现null在那种情况下.
是的,它总是被定义的。
documentElement 属性以 Element 对象的形式返回文档的 documentElement。对于 HTML 文档,返回的对象是
<html>元素。该属性是只读的。
https://www.w3schools.com/jsref/prop_document_documentelement.asp
虽然document.body如果脚本从标签运行<head>并且页面未完全加载,则可以为 null,<html>但元素始终存在于 html 文档中。
| 归档时间: |
|
| 查看次数: |
1969 次 |
| 最近记录: |