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?
new MutationObserver
andnew WebKitMutationObserver
. They share same outcome. – Echoismdocument.querySelector('body')
, just usedocument.body
. – Atomize