JavaScript › DOM & Events
How does MutationObserver let you react to DOM changes made by other code?
AdvancedAnswer
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.