8

From http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers I got the following code:

var insertedNodes = [];
var observer = new WebKitMutationObserver(function(mutations) {
 alert('run');
 mutations.forEach(function(mutation) {
   for (var i = 0; i < mutation.addedNodes.length; i++)
     insertedNodes.push(mutation.addedNodes[i]);
 })
});
observer.observe(document, { childList: true });
console.log(insertedNodes);

var divElement = document.createElement('div');
divElement.innerHTML = 'div element';
document.querySelector('body').appendChild(divElement);

jsFiddle: http://jsfiddle.net/cUNH9

As you can see , we should see a alert because a div element is inserted to the DOM. But it appears MutationObserver codes don't run. How can I successfully make the MutationObserver code run?

sideshowbarker
  • 62,215
  • 21
  • 143
  • 153
weilou
  • 3,869
  • 8
  • 37
  • 56

1 Answers1

12

Add subTree option as well, it should work, you want to monitor not just children of document ( head/body) but it's descendants as well. (And that is the reason when set to document.body it works).

observer.observe(document, {
    attributes: true,
    childList: true,
    characterData: true,
    subtree:true
});

Fiddle

From documentation

subtree: Set to true if mutations to not just target, but also target's descendants are to be observed.

So what you are adding is a descendant of the document not its child (or direct descendant). It is a child of body (and that is why just mentioning childList and using document.body works). You need to mention subTree if you want to monitor the changes deep.

Also see the note as well:

NOTE: At the very least, childList, attributes, or characterData must be set to true. Otherwise, "An invalid or illegal string was specified" error is thrown.

PSL
  • 120,386
  • 19
  • 245
  • 237
  • 2
    @plalx No. Subtree is required, if he wants to monitor deep in body as well, ex, if he wants to add anothe div inside this div. – PSL Oct 03 '13 at 04:13
  • 1
    @plalx check this example remove subtree and try as well. http://jsfiddle.net/9wtDc/ – PSL Oct 03 '13 at 04:14
  • @PSL, Right, my bad ;) – plalx Oct 03 '13 at 05:17
  • @PSL It doesn't work in Firefox. Is there alternative? – cainhs Nov 09 '16 at 06:38
  • @cainhs MDN says it should work with firefox as well. – PSL Nov 09 '16 at 22:55
  • 1
    @PS I found the issue. I should not monitor the document.body in Firefox as the DOM is not ready. (i.e. it is empty) during page load. Instead, create a main div in the body and observe that. I wonder why Firefox behaves differently from Chrome and IE. – cainhs Nov 17 '16 at 01:05