Reputation: 65
Question is simple but confusing for me that when i console.log(document.body) or (document.head) both are working fine but when i do with document.script or document.html these two are not working why ? although all these things are in the document ?
Q2) i can write
document.getElementById('something')
but why i can't write
document.body.getElementById('something')
although body is in the document and element in the body tag as well, while sometime document.body works at different stages in script
Upvotes: 1
Views: 104
Reputation: 1074208
getElementById
is a method on document
, which is an object that uses the Document
interface from the DOM. It's not a method on elements (the Element
interface from the DOM and its specialization the HTMLElement
interface from HTML). document.body
is an element (an HTMLBodyElement
, which is an HTMLElement
, which is an Element
), not a document.
Some methods (like querySelector
) are methods on both document
and elements, because it makes sense for them to be (on an element, querySelector
only looks within the element, not throughout the document). But getElementById
isn't. (It could be, but it would be a bit odd to scope it to just an element when IDs are meant to be unique throughout the document.)
Upvotes: 6