Hint
Watch for DOM changes asynchronously — replaces deprecated Mutation Events
MutationObserver watches for changes to the DOM tree and fires a callback when changes occur — batched and asynchronous.
const observer = new MutationObserver((mutations, obs) => {
mutations.forEach(mutation => {
if (mutation.type === 'childList') {
console.log('Added:', mutation.addedNodes);
console.log('Removed:', mutation.removedNodes);
}
if (mutation.type === 'attributes') {
console.log('Attr changed:', mutation.attributeName, 'on', mutation.target);
}
if (mutation.type === 'characterData') {
console.log('Text changed');
}
});
});
observer.observe(document.getElementById('app'), {
childList: true, // watch add/remove of child nodes
attributes: true, // watch attribute changes
characterData: true, // watch text content changes
subtree: true, // observe all descendants too
});
observer.disconnect(); // stop observing
Use cases: Lazy loading, detecting when third-party code modifies the DOM, building virtual DOM diffing, accessibility announcements.