sajad torkamani

Main purpose

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

  • Run code when any DOM node is added
  • Run code when a DOM node with a specific selector is added
  • Run code when the class attribute of a DOM node is updated.

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:

  • MutationRecord.type: A string representing the type of the mutation:
    • attributes: An attribute was mutated.
    • childList: The tree of nodes was mutated (e.g., because a node was added or removed).
    • characterData: A CharacterData node was mutated.
  • MutationRecord.target: The node the MutationRecord affected,  depending on the MutationRecord.type:
    • For attributes, it is the element whose attribute changed.
    • For characterData, it is the CharacterData node.
    • For childList, it is the node whose children changed.

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)

observer.disconnect();

Links

Tagged: Web APIs