w3c / dom

Moved to https://dom.spec.whatwg.org/
60 stars 18 forks source link

Mutation Observer not creating mutations for nodes added through innerHTML #166

Open ghost opened 6 years ago

ghost commented 6 years ago

Adding internal nodes through innerHTML does not cause an addedNode in the mutation record for the internal node. For example: Let's suppose if we have a div element and have a Mutation Observer running observing the document

div.innerHTML = "<div><img></img></div>";

This would lead to just one addedNode in the mutation having "div" as the addedNode and "img" as one of the childNodes. But, there is no separate addedNode for "img" node added.

<html>
  <head>
    <script>
      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);
                    break;
              default:
            }
        }
      });

      observer.observe(document.documentElement, {
        childList: true,
        subtree: true,
        attributes: true
      });
    </script>
  </head>
  <body>
    <div id="first">
      <div>
        <img></img>
      </div>
    </div>
    <div id="second">
    </div>
  </body>
  <script>
    console.log("-----------------");
    document.getElementById("second").innerHTML = "<div><img></img></div>";
  </script>
</html>

It just logs one addedNode in the mutation for the "second" div, though the HTML structure for both "first" and "second" div is same.

yongsheng commented 6 years ago

I think the behavior now is for the 'root' node of the fragment to be inserted. Not sure it'll hurt perf if subtree is included.