Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MutationObserver?

I recently came across this awesome MutationObserver feature which sort of keep tracks of the changes on any dom element. I used the code that was shown on the mozilla developer network, but can't seem to make it run. This is the code I used (link):

   // create an observer instance
var target = document.querySelector('#something');
console.log(target);
var observer = new WebKitMutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      console.log("Success");
        //$('#log').text('input text changed: "' + target.text() + '"');
        //console.log(mutation, mutation.type);
    });    
});
observer.observe(target, { attributes: true, childList: true, characterData: true });
//observer.disconnect(); - to stop observing

// test case
setInterval(function(){
    document.querySelector('#something').innerHTML = Math.random();
},1000);

The above code doesn't seems to work. However if I modify the same code with a bit of jQuery, everything seems to work just fine (Demo here). Is there something I'm missing from the docs or I'm just misinterpreting the observer feature.

like image 451
I_Debug_Everything Avatar asked Jun 21 '14 17:06

I_Debug_Everything


People also ask

What can MutationObserver do?

MutationObserver can react to changes in DOM – attributes, text content and adding/removing elements. We can use it to track changes introduced by other parts of our code, as well as to integrate with third-party scripts. MutationObserver can track any changes.

What is window MutationObserver?

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.

How do you stop MutationObserver?

disconnect() The MutationObserver method disconnect() tells the observer to stop watching for mutations. The observer can be reused by calling its observe() method again.

Does react use MutationObserver?

Use a useEffect() hook that depends on the values of callback and options . Check if the given ref is initialized. If it is, create a new MutationObserver and pass it the callback .


1 Answers

You need subtree: true

http://jsfiddle.net/6Jajs/1/

The inner text would normally be a child text() element in the DOM. Without the subtree it will only watch the element itself.

There is possible confusion surrounding "characterData" (https://developer.mozilla.org/en-US/docs/Web/API/CharacterData), but it seems that that applies only to nodes that directly contain text. The DOM is structured so that most markup elements contain mixed type which optionally include a child text node (which in turn would implement characterData, but would be a child of the targeted node).

like image 94
Matt Whipple Avatar answered Oct 13 '22 02:10

Matt Whipple