When we try to add nested nodes in DOM using appendChild or innerHTML, the nested nodes do not come in the addedNodes of a mutation.
Initial HTML setUp:
<html> <body> <div id="container"> </div> </body> </html> Here is my Mutation Observer code:
var observer = new MutationObserver(function(mutations) { for (var i = 0; i < mutations.length; i++) { var mutation = mutations[i]; switch(mutation.type) { case 'childList': console.log(mutation.addedNodes); break; default: } } }); observer.observe(document, { childList: true, subtree: true, attributes: true, characterData: true }); If I now do appendChild with a nested img node in a div,
var img = document.createElement('img'); img.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png"); var div = document.createElement('div'); div.appendChild(img); var container = document.getElementById("container"); container.appendChild(div); The Mutation Observer only logs the div which is appended to the container, but does not log the img as an addedNode in mutation.
Here is a working JSFiddle: https://jsfiddle.net/aedhefhn/
Is there a workaround for this?