JAVASCRIPT
Observing DOM Subtree Modifications with MutationObserver
Learn to use MutationObserver to efficiently detect and react to changes in the DOM, such as element additions/removals or attribute modifications.
const targetNode = document.getElementById('myContainer');
const config = {
attributes: true,
childList: true,
subtree: true,
attributeFilter: ['class', 'id'] // Optional: only observe specific attributes
};
const callback = (mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
console.log('Added nodes:', mutation.addedNodes);
console.log('Removed nodes:', mutation.removedNodes);
} else if (mutation.type === 'attributes') {
console.log(`The '${mutation.attributeName}' attribute was modified.`);
console.log('Old value:', mutation.oldValue); // Requires attributeOldValue: true in config
}
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
// --- Example of DOM changes to observe (run these after observer is set up) ---
// targetNode.appendChild(document.createElement('p'));
// targetNode.children[0].setAttribute('data-new', 'value');
// targetNode.removeChild(targetNode.children[0]);
// observer.disconnect(); // Stop observing changes
How it works: This snippet demonstrates how to use the `MutationObserver` API to watch for changes within a specific DOM element and its subtree. It configures the observer to detect additions or removals of child nodes (`childList: true`), and modifications to element attributes (`attributes: true`), optionally filtering for specific attributes. The `callback` function is executed whenever a configured change occurs, providing detailed information about the mutations. This is highly useful for reacting to dynamic content updates, third-party script manipulations, or debugging unforeseen DOM changes without constant polling.