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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With