Home > OS >  Why MutationObserver doesn't make a callback
Why MutationObserver doesn't make a callback

Time:07-17

What could be a reason why the following code doesn't fire MutationObserver callbacks ?

<!DOCTYPE html>
<body>
  <div id="msg">Hello</div>
  <script>
    var el = document.getElementById("msg");
    var obs = new MutationObserver(() => {
      console.log("Changed!");
    });
    obs.observe(el, {subtree: true, characterData: true});
    setTimeout(() => {
        el.innerHTML  = " World!";
    }, 3000);
  </script>
</body>
</html>

CodePudding user response:

innerHTML alters the DOM, so you need to monitor childList.

<!DOCTYPE html>
<body>
  <div id="msg">Hello</div>
  <script>
    var el = document.getElementById("msg");
    var obs = new MutationObserver(() => {
      console.log("Changed!");
    });
    obs.observe(el, {childList: true});
    setTimeout(() => {
        el.innerHTML  = " World!";
    }, 3000);
  </script>
</body>
</html>

  • Related