首页 > 解决方案 > 为什么 document.getElementById() 函数不存在于 window.document 对象中?

问题描述

我想知道为什么对象document.getElementById()内部document.getElementsByClassName()不存在类似函数window.document。我错过了什么吗?

标签: javascript

解决方案


因为它们在文档级别而不是窗口级别工作。这正是他们适合的地方。所以它们是在Documentinterface上定义的。(一些,如geElementsByClassName,querySelectorquerySelectorAll也在级别定义;它们仅该元素内工作。)Element

一方面是您可以使用多个文档。例如,DOMParser创建文档:

const doc = new DOMParser().parseFromString(
    `<div id="x">hi</div>`,
    "text/html"
);

// The following shows a div with "hi" in it
console.log(doc.getElementById("x"));

// The following shows `null`, because there isn't any `id="x"` element
// in `document`
console.log(document.getElementById("x"));

虽然你可以有一个window.getElementById刚刚转身并做的事情window.document.getElementById,但没有充分的理由这样做。它更适合document.


推荐阅读