Search code examples
javascriptmutation-observers

MutationObserver is not triggered when innerText changes


I am running a JavaScript file on this URL. I am interested in changes in the red outlined elements:

enter image description here

I wrote the following script

const $xpath = xp => {
  const snapshot = document.evaluate(
    xp, document, null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
  );
  return [...Array(snapshot.snapshotLength)]
    .map((_, i) => snapshot.snapshotItem(i));
};

const xpathOdds = './/div[@col-id="bestOdds"]/descendant::div[@class="d-flex justify-content-between align-items-center"]';
var odds = $xpath(xpathOdds);
var config = {characterData: true,
              attributes: true,
              childList: true,
              subtree: true
};

odds.forEach(function(target, idx) {
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        console.log(mutation);
    });
  });
  observer.observe(target, config);
})

I am not sure why the MutationObserver is not triggered. It is triggered if I edit an element using right mouse click - "Inspect". However, it is not triggered if the website itself makes changes to the elements in question. When an element changes it becomes yellow, so I know there should have been mutations. What am I doing wrong?


Solution

  • I checked the link you posted, and I think the problem is you are attaching the observers to the wrong objects. The thing is, when there is an update and the color of the cell becomes yellow, the whole table get replaced and not just the cells. So the cells you were observing are no longer there to be observed. You should attach the observer to a higher element in the hierarchy that does not get replaced, like that one with the class ag-center-cols-viewport or the document itself.