Home > Net >  mutation observer wont do anything but no error is shown
mutation observer wont do anything but no error is shown

Time:11-12

Hi,

I have this code:

<div id="container" data-room="room1">some content</div>
<button onclick="changeroom('room2');">Change</button>

and this mutation observer is supposed to execute a function when the data in data-room changes

new MutationObserver(() => {
      const lastroom = "room1"; 
      if (document.getElementById("container").dataset.room !== "room1") {
      console.log('changed room')
      }
     }).observe(document, {subtree: true, childList: true});

but it does nothing at all. You can test it here: https://jsfiddle.net/5hdjfg4t/

why is that?

Thank you.

CodePudding user response:

You're not adding or removing any elements, so an observer of childList does not fire. You need to observe for changes to attributes instead.

const container = document.getElementById("container");

function changeroom(room) {
  container.dataset.room = room;
}

new MutationObserver(() => {
  if (container.dataset.room !== "room1") {
    console.log('changed room')
  }
}).observe(container, {
  attributes: true
});
<div id="container" data-room="room1">some content</div>
<button onclick="changeroom('room2');">
Change
</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Well you are changing an attribute and you did not tell it to listen for attribute changes

subtree: true, 
childList: true,
attributes: true,
  • Related