6/7/2016 - 12:07 PM

Detect changes in the DOM with MutationObserver

Detect changes in the DOM

Using MutationObserver and falling back to the deprecated Mutation events if needed:
(Example below if only for DOM changes concerning nodes appended or removed) 
IE9+, FF, Webkit

var observeDOM = (function(){
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
        eventListenerSupported = window.addEventListener;

    return function(obj, callback){
        if( MutationObserver ){
            // define a new observer
            var obs = new MutationObserver(function(mutations, observer){
                if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
            // have the observer observe foo for changes in children
            obs.observe( obj, { childList:true, subtree:true });
        else if( eventListenerSupported ){
            obj.addEventListener('DOMNodeInserted', callback, false);
            obj.addEventListener('DOMNodeRemoved', callback, false);

// Observe a specific DOM element:
observeDOM( document.getElementById('dom_element') ,function(){ 
    console.log('dom changed');