A simple mutation observer example in JavaScript does not work

I am trying to add MutationObserver to my webpage to get changes in img src, but this does not work.

The code used here is:

 setTimeout(function() { document.getElementById("img").src = "http://i.stack.imgur.com/aQsv7.jpg" }, 2000); var target = document.querySelector('#img'); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.log(mutation.type); }); }); var config = { attributes: true, childList: false, characterData: false }; observer.observe(target, config); observer.disconnect(); 
 <img src="http://i.stack.imgur.com/k7HT5.jpg" id="img" class="pic" height="100"> 
+6
source share
1 answer

If you call the disconnect method, you will no longer receive notifications:

Quote from MDN

 disconnect() 

Stopping the MutationObserver instance from receiving DOM mutation notifications. Until the watch () method is used again, the callback will not be called.

 setTimeout(function() { document.getElementById("img").src = "http://i.stack.imgur.com/aQsv7.jpg" }, 2000); setTimeout(function() { document.getElementById("img").src = "http://i.imgur.com/Xw6htaT.jpg" }, 4000); var target = document.querySelector('#img'); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.log(mutation.type); }); }); var config = { attributes: true, childList: false, characterData: false }; observer.observe(target, config); // otherwise observer.disconnect(); observer.observe(target, config); 
 <img src="http://i.stack.imgur.com/k7HT5.jpg" id="img" class="pic" height="100"> 
+9
source

Source: https://habr.com/ru/post/986040/


All Articles