When I needed to add an element to the head
or body
of a document, I used to reach for document.querySelector()
, the Swiss-Army knife of document
methods:
const headNode = document.querySelector('head')
const bodyNode = document.querySelector('body')
console.log(`I'm the head:`, headNode)
console.log(`I'm the body:`, bodyNode)
This works and is a familiar pattern for finding DOM elements.
Today I learned about document.head
and document.body
, which provide query-free references to the head
and body
elements of the document, respectively!
Which these handy references, we can replace the previous code block with:
console.log(`I'm the head:`, document.head)
console.log(`I'm the body:`, document.body)
No more creating variables to reference body
and head
; they're always available on the document
object.
document.head
and document.body
are available in all browsers after IE8: checkout the availability chart on CanIUse.com.
Happy coding!
Top comments (0)