Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I observe the whole body with MutationObserver? [duplicate]

I want a certain function to be called whenever another script adds a div to the body.

I tried:

var dom_observer = new MutationObserver(function(mutation) {
    console.log('function called');
});
var container = document.body;
console.log(container);
var config = { attributes: true, childList: true, characterData: true };
dom_observer.observe(container, config);

I tried setting container to document.body (example above) and to document.querySelector('body'). In both cases, console.log() displayed null and I got the following error: TypeError: Argument 1 of MutationObserver.observe is not an object.. The callback function was not called when a div was added to the body.

I tried setting it to document.getElementsByTagName("body")[0] and to document.documentElement.childNodes[1]. In both cases, console.log() displayedundefined and the callback function was still never called.

like image 856
Mat Avatar asked Jul 15 '17 11:07

Mat


Video Answer


1 Answers

The problem is that you're setting the target as document, and not container. To make sure this is cross-browser compatible, use document.documentElement along with document.body. The following should work:

var dom_observer = new MutationObserver(function(mutation) {
    console.log('function called');
});
var container = document.documentElement || document.body;
console.log(container);
var config = { attributes: true, childList: true, characterData: true };
dom_observer.observe(container, config);

Working JSFiddle

like image 175
Jacques Marais Avatar answered Oct 13 '22 08:10

Jacques Marais