Reacting to Changes

MutationObserver is a powerful built-in object that allows you to " watch " the DOM tree for changes and react to them automatically.

What can it see?

  • Adding or removing child elements.
  • Changing attributes (like class, style, or id).
  • Changing text content.
let observer = new MutationObserver(mutations => {
  for(let mutation of mutations) {
    console.log("Change detected:", mutation.type);
  }
});

observer.observe(document.body, {
  childList: true, // watch for added/removed children
  subtree: true,   // watch all descendants, not just direct children
  attributes: true // watch for attribute changes
});
Tip

This is far more CPU-efficient than using a timer (setInterval) to constantly check if something on the page has changed.

Caution

Always remember to call observer.disconnect() when you no longer need to watch the element. Otherwise, the observer keeps running in the background, which can cause severe memory leaks!