How does MutationObserver let you react to DOM changes made by other code?
Short answer
MutationObserver watches a target node (and optionally its subtree) for changes like added/removed children, attribute changes, or text changes, and asynchronously batches callbacks — useful for reacting to DOM mutations from third-party scripts you don't control.
Advertisement
AModel answer
MutationObserver watches a target node (and optionally its subtree) for changes like added/removed children, attribute changes, or text changes, and asynchronously batches callbacks — useful for reacting to DOM mutations from third-party scripts you don't control.
const observer = new MutationObserver((mutations) => {
mutations.forEach(m => console.log(m.type, m.target));
});
observer.observe(document.body, { childList: true, subtree: true });Real-world example
Detecting when a third-party widget injects new DOM nodes so your code can style or enhance them.
Likely follow-ups
- How does MutationObserver differ from the older, deprecated Mutation Events?
Related topics