DEV Community

Cover image for πŸ” MutationObserver: Sherlock Holmes of the Web
S. M. Faizul Islam Fair
S. M. Faizul Islam Fair

Posted on

πŸ” MutationObserver: Sherlock Holmes of the Web

πŸ€” Suppose you have an interactive website where elements are constantly changing, text updates and new content sneaks in. You need a detective to watch all of this. Use MutationObserver, JavaScript’s Sherlock Holmes, who never misses a detail. Once something changes, the detective detects the change and decides what action to take. πŸš€


πŸ’‘ Example: Sherlock Holmes Investigates Price Updates πŸ’°

Let’s say you have a shopping cart on your website, and the price of the cart updates whenever an item is added or removed. You need Sherlock Holmes (MutationObserver) to catch these updates and notify you.

// Select the node that will be observed for mutations
const cartPrice = document.getElementById("cart-price");

// Options for the observer (which mutations to observe)
const config = { 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("πŸ•΅οΈ Sherlock noticed an item added or removed from the cart: Price updated!");
    } 
    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(cartPrice, config);

Enter fullscreen mode Exit fullscreen mode

🧐 What’s Happening Here?

  • Setup: The target node, the cart price, is being observed.
  • Detecting Changes: If an item is added or removed from the cart, Sherlock reports it.
  • Action: Sherlock detects and logs the changes, notifying you of any price updates.

βš™οΈ Use MutationObserver when you want to:

  • Track dynamic changes to your webpage.
  • Detect the addition or removal of DOM elements.
  • Listen for changes in attributes or content.
  • Dynamically update UI components in response to changes in other parts of the DOM

🎩 Wrapping It Up

Just like Sherlock Holmes always finds the hidden clues, MutationObserver keeps track of any sneaky changes on your webpage. Whether it’s an added element, a modified attribute, or some other mysterious shift, MutationObserver will catch it and report it back to you! πŸ₯³

Top comments (0)