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)