The MDN documentation for MutationObserver.observe()
states that the first parameter passed into observe()
should be “A DOM Node (which may be an Element) within the DOM tree to watch for changes, or to be the root of a subtree of nodes to be watched.” All the examples I’ve seen for high-level DOM observation advise passing in document.body
here, but can you actually pass in document
instead to observe both the body and head in one observer (or for that matter, observe the body
once it’s added, if the body
does not yet exist at the time your JS is executing)?
This seems to work in Chrome, but is that non-standard behaviour by Chrome or is it legal according to the spec?
Advertisement
Answer
The good news is that it is totally possible/legal to pass document
into observe()
. My guess as to why guides usually pass document.body
in is simply to avoid observing unwanted mutations of the head
and also potentially DOM elements that haven’t yet been attached to the body.