JAVASCRIPT
Real-time DOM Change Detection with MutationObserver
Learn how to use JavaScript's MutationObserver API to efficiently detect and react to changes in the DOM structure, attributes, or text content without polling.
const targetNode = document.getElementById('myDynamicContainer');
if (targetNode) {
const config = {
attributes: true,
childList: true,
subtree: true,
characterData: true
};
const callback = function(mutationsList, observer) {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.', mutation.target);
// Example: re-render a list if children change
} else if (mutation.type === 'attributes') {
console.log(`The "${mutation.attributeName}" attribute was modified on:`, mutation.target);
// Example: react to class changes for styling
} else if (mutation.type === 'characterData') {
console.log('The text content has changed on:', mutation.target);
}
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
// Example changes to trigger the observer
// setTimeout(() => {
// const newDiv = document.createElement('div');
// newDiv.textContent = 'New content added!';
// targetNode.appendChild(newDiv);
// targetNode.setAttribute('data-status', 'updated');
// }, 2000);
// To stop observing later:
// observer.disconnect();
} else {
console.error('Target node #myDynamicContainer not found.');
}
How it works: The MutationObserver API allows you to watch for changes being made to the DOM tree. You define a `targetNode` to observe and a `config` object specifying which types of changes (attributes, child elements, text content, subtree changes) to monitor. The `callback` function is executed whenever a configured change occurs, receiving a list of `MutationRecord` objects detailing each change. This is highly efficient compared to polling and essential for reacting to third-party script changes or complex UI updates.