繁体   English   中英

document.documentElement 什么时候可以为空?

[英]When can document.documentElement be null?

我遇到了 Flow 的一个用例,当我使用document.documentElement我需要首先对它进行类型优化,因为它有可能在其内置定义中定义为 null。

https://github.com/facebook/flow/blob/8391250177e37a047a33ae728fdbd1138632294a/lib/dom.js#L824

const { documentElement } = document;
if (documentElement instanceof HTMLElement) {
  // continue doing stuff
}

做一个简单的谷歌不会产生任何结果,为什么会这样。 所以我的问题是这个值什么时候可以为空或者是 lib defs 的错误?

我认为它直接来自规范的类型定义。 在“空文档”的情况下, Document#documentElement可能是任何元素或没有元素。 您可以构造Document ,因此可能存在它不是HTMLElement 这似乎有点做作,但我认为类型应该考虑所有情况。 因此,如果您有一个文档,它可能会失败。

来自 MDN

对于任何非空 HTML 文档, documentElement将始终是<html>元素。 对于任何非空的 XML 文档, documentElement将始终是documentElement的根元素。

 const d = new Document(); console.log(`document.documentElement: ${document.documentElement instanceof HTMLElement}`); console.log(`d.documentElement: ${d.documentElement instanceof HTMLElement}`);

暂无
暂无

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

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