How to use MutationObserver () correctly?

6

I know that MutationObserver() is designed to detect changes in the HTML DOM.

But I wonder how this works in practice.

We created a hypothetical situation, what's up?

There is a <div> with id='hipotese' (I believe it will be observed by its id , correct?)

It is <div> has several other contents inside it, which are generated dynamically. (we do not have control of the amount of content generated within it)

What happens is that there are several methods that act on these dynamic content. (receive various parameters from these contents)

In Google Chrome we can tighten the F12 and leave changing the attributes of this content in any way we want.

- End of hypothetical situation -

How can I observe and detect the smallest and simplest change in these elements present in our <div id='hipotese'> ?

Is there any other way to detect this change?

I know that the user can disable JavaScript , but nothing that can not be resolved with <noscript>     

asked by anonymous 02.08.2017 / 18:39

1 answer

1

When you register the instance to receive notifications using the watch you can pass an object specifying which mutations should be observed.

You can see the options available at MutationObserverInit .

Below is a snippet that exemplifies the changes.

var hipotese = document.getElementById('hipotese');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log('mutation.type = ' + mutation.type);
    if (mutation.type === 'childList') {
    	for (var i = 0; i < mutation.addedNodes.length; i++) {
        console.log('  "' + mutation.addedNodes[i].textContent + '" adicionado');
      }

      for (var i = 0; i < mutation.removedNodes.length; i++) {
        console.log('  "' + mutation.removedNodes[i].textContent + '" removido');
      }
    } else {
    	console.log('  "' + mutation.attributeName + '" alterado')
    }
  });
});

observer.observe(hipotese, {
  childList: true,
  attributes: true,
  characterData: true,
  subtree: true,
  attributeOldValue: true,
  characterDataOldValue: true
});

hipotese.className = 'pai';
var filho = document.createElement('div');
filho.textContent = 'filho';
hipotese.appendChild(filho);
filho.className = 'filho';
filho.dataset.teste = 'teste';
hipotese.removeChild(filho);
<div id="hipotese"></div>
    
30.10.2017 / 19:36