With the MutationObserver WebAPI, you can watch for changes being made to the DOM tree. This is the API you use when you want to check if an element has been added or removed from the page, or if there has been any changes made to an element on a page.

Checkout the code snippet below to see how it works

// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-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 = (mutationList, observer) => {
  for (const mutation of mutationList) {
    if (mutation.type === 'childList') {
      console.log('A child node has been added or removed.');
    } else if (mutation.type === 'attributes') {
      console.log(`The ${mutation.attributeName} attribute was modified.`);
    }
  }
};
// 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);
// Later, you can stop observing
observer.disconnect();

Reference – https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Categorized in: