简体   繁体   中英

Mutation Observer does not detect nodes added through innerHTML, appendChild

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?

That is the expected behavior. The div was all that was appended, it just happened to have some children. You can certainly walk through its child nodes yourself from .addedNodes though. .addedNodes is just an array of nodes, so you can go through each item recursively to get all the children.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM