Search code examples
javascriptmutation-observers

mutation observer wont do anything but no error is shown


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.


Solution

  • 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>