文档对象模型
Document Object Model
问题很简单,但让我感到困惑的是,当我 console.log(document.body) 或 (document.head) 两者都工作正常但是当我使用 document.script 或document.html 这两个为什么不起作用?尽管所有这些都在文档中?
Q2) 我会写
document.getElementById('something')
可是为什么我写不出来
document.body.getElementById('something')
虽然正文在文档中,元素也在正文标签中,但有时 document.body 在脚本的不同阶段工作
getElementById
是 document
上的一个方法,它是一个使用来自 HTML 的 Document
interface from the DOM. It's not a method on elements (the Element
interface from the DOM and its specialization the HTMLElement
接口的对象。 document.body
是一个元素(一个 HTMLBodyElement
,一个 HTMLElement
,一个 Element
),而不是一个文档。
一些方法(如querySelector
)是document
和元素的方法,因为它使得感觉它们是(在一个元素上,querySelector
只在元素内查找,而不是在整个文档中查找)。但是 getElementById
不是。 (可能是,但是当 ID 在整个文档中是唯一的时,将其范围限定为一个元素会有点奇怪。)
问题很简单,但让我感到困惑的是,当我 console.log(document.body) 或 (document.head) 两者都工作正常但是当我使用 document.script 或document.html 这两个为什么不起作用?尽管所有这些都在文档中?
Q2) 我会写
document.getElementById('something')
可是为什么我写不出来
document.body.getElementById('something')
虽然正文在文档中,元素也在正文标签中,但有时 document.body 在脚本的不同阶段工作
getElementById
是 document
上的一个方法,它是一个使用来自 HTML 的 Document
interface from the DOM. It's not a method on elements (the Element
interface from the DOM and its specialization the HTMLElement
接口的对象。 document.body
是一个元素(一个 HTMLBodyElement
,一个 HTMLElement
,一个 Element
),而不是一个文档。
一些方法(如querySelector
)是document
和元素的方法,因为它使得感觉它们是(在一个元素上,querySelector
只在元素内查找,而不是在整个文档中查找)。但是 getElementById
不是。 (可能是,但是当 ID 在整个文档中是唯一的时,将其范围限定为一个元素会有点奇怪。)