Confused About MutationObserver

Knight Yoshi picture Knight Yoshi · May 18, 2013 · Viewed 9.5k times · Source

So I have been rattling my brain about using the MutationObserver and I haven't made any progress. I've read about it on the W3C site and in the MDN. When reading it in the MDN, everything made sense until the example.

// select the target node
var target = document.querySelector('#some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });   
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
observer.disconnect();

The part I'm having the most trouble with is creating the observer instance, not sure the syntax of what belongs there. Also in the console I've been getting a "TypeError: Value does not implement interface Node." No matter which examples I've looked at and tried using; replacing the selectors in the example with the desired jQuery selectors (also non-jQ selectors returned the same problem).

Answer

Jabher picture Jabher · Jul 25, 2013

first you definitely should not use jQ selectors as they are not Node elements. second, you must be sure that query selector returns not null. To make sure try for the first time observer on document.body: it is definitely a Node object. Something like

(
    new MutationObserver(function(mutationEventList){
        console.log(mutationEventList)
    })
)
.observe(document.body, {
    childList: true,
    attributes: true,
    characterData: true
})

When you will get familiar with targeting an observer and understand MutationObserverInit options values(they are described not as good as it could) you will be able to work with mutationObserver right.