javascript - 为什么 document.getElementById() 函数不存在于 window.document 对象中?
问题描述
我想知道为什么对象document.getElementById()
内部document.getElementsByClassName()
不存在类似函数window.document
。我错过了什么吗?
解决方案
因为它们在文档级别而不是窗口级别工作。这正是他们适合的地方。所以它们是在Document
interface上定义的。(一些,如geElementsByClassName
,querySelector
等querySelectorAll
也在级别定义;它们仅在该元素内工作。)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
.
推荐阅读
- python - 有没有办法从 face_recognition 中消除面部标志?也许通过 PIL?
- android - 是否可以在 android 应用程序中构建/导出 android 应用程序?
- c++ - 在衰减方面是否对布尔数组进行了不同的处理?
- postgresql - 缺少 PostgreSQL 10.6_1 扩展
- php - POST 数据中缺少动态生成的表单元素
- python - 找到正确的正则表达式来聚合日志?
- c# - 如何将 C# 字节数组转换为二进制字符串以粘贴到 SQL 脚本中?
- bash - bash:在脚本末尾 pushd 后不需要调用 popd 吗?
- .net-core - 运行 Update-database 或 Enable-migration 时失败并出现错误“异常调用“SetData”和“2”参数”,
- python - 根据教程图不需要使用,但在vscode中收到未使用的变量错误