sajad torkamani

Main purpose

The MutationObserver API lets you watch for changes to the DOM tree and invoke callbacks. Example use cases include:

Example usage: Listen for DOM nodes being added

1. Define callback to be executed on mutations

This callback function will be executed whenever the specific mutations (configured later) are detected.

const callback: MutationCallback = (mutations, observer) => {
    for (const mutation of mutations) {
        if (mutation.type === 'childList' && mutation.addedNodes.length) {
            mutation.addedNodes.forEach((node) => {
                if (node.nodeType === Node.ELEMENT_NODE) {
                    const element = node as Element;
                    if (requiredClasses.every(cls => element.classList.contains(cls))) {
                        console.log('New node with the required classes added:', element);
                        // Perform any additional actions with the element

mutations in the above example is an array of MutationRecord objects. See the API for more details but the key information available is:

2. Create MutationObserver instance

const observer = new MutationObserver(callback);

3. Configure the observer

Specify the types of mutations you want to observe

const config: MutationObserverInit = {
    childList: true, // Observe changes to child nodes
    subtree: true // Observe the entire subtree in addition to the child nodes

4. Start observing the target node for configured mutations

const targetNode = document.body; // You can choose a more specific part of your DOM structure if necessary
observer.observe(targetNode, config);

5. Stop observing if no longer needed (e.g., when a React component unmounts) (Optional)