user16691768
user16691768

Reputation: 113

MutationObserver doesnt detect changes inside querySelectorAll()[]

I hav this code.

New MutationObserver(() => {
  const code = document.querySelectorAll('code');
  const parser = JSON.parse(code[10].textContent as string);
  const getData = parser.elements;

  console.log(getData);

 }).observe(document, {
  attributes: true,
  characterData: true,
  childList: true,
  subtree: true,
  attributeOldValue: true,
  characterDataOldValue: true,
});

Currently, MutationObserver doesn't detect the new querySelectorAll('code')[10].textContent content in next page.

What do I need to do to detect that changes?

Upvotes: 0

Views: 1048

Answers (1)

Moshe Sommers
Moshe Sommers

Reputation: 1506

The callback passed into the MutationObserver constructor is what's called when a mutation is observed NOT what's being observed.

You need to call the observe function on your observer with the config of what to observe

// Node to observe
const targetNode = document.getElementById('#id');
//Options for the observer (which mutations to observe)

const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    .....
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

Check out the docs here

Upvotes: 1

Related Questions