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

标签 javascript dom flowtype

我遇到了一个 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 s,所以在某些情况下它可能不是 HTMLElement .这似乎有点做作,但我认为这些类型应该解释所有情况。因此,如果您有一个文档,它可能会失败。

From MDN :

For any non-empty HTML document, documentElement will always be an <html> element. For any non-empty XML document, documentElement will always be whatever element is the root element of the document.

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

关于javascript - document.documentElement 什么时候可以为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64028461/

相关文章:

javascript - `Array.prototype.slice.call` 是如何工作的?

javascript - 使用正则表达式将文本替换为列表中的标记

javascript - jQuery 不支持 .has 在 IE8 中?什么是解决方法?

javascript - 如何将整个模块的类型分配给解构变量?

javascript - 如何将 Flow 与外部高阶组件包装器一起使用

javascript - VSCode 中的流类型检查性能

javascript - 当具有渲染器的 DOM 元素不在屏幕顶部时移动场景的坐标

javascript - 在 javascript 解释器环境中使用 parse

javascript - 通过表单 ID 访问单选按钮值

javascript - 如何向整个 HTML 添加或应用 CSS 类