How to use the Mutationobserver() of the correct vein?

Asked

Viewed 1,723 times

7

I know that the MutationObserver() was developed to detect HTML DOM changes.

But I’d like to know how it works in practice.

We create a hypothetical situation, how about?

There is a <div> with id='hipotese' (I believe she will be watched by your id, correct?)

Is <div> has several other contents within it, which are generated dynamically. (we have no control over the amount of content generated within it)

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

In Google Chrome we can press F12 and exit changing the attributes of this content in any way we want. And once changed when the call of methods happened, the returns would not be as expected (dynamically generated)

-- End of the hypothetical situation --

As I can 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 the user can disable the JavaScript, but nothing that cannot be solved with the <noscript>

  • The part "What happens is that there are several methods that act in these dynamic contents" was particularly confusing for me. These methods are functions that alter content based on itself, since the parameters come from this?

1 answer

2

When you register the instance to receive notifications with the method observe you can pass an object specifying which mutations should be observed.

You can see the options available at Mutationobserverinit.

Below is a snippet illustrating 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.