Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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

subtree: true, 
childList: true,
attributes: true,
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!