Syntax
new MutationObserver(callback).observe(target, options)Examples
Watching for Added Child Elements
Reacting whenever new elements are added to a container.
const container = document.querySelector("#chatMessages");
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
if (mutation.addedNodes.length > 0) {
console.log("New message added, scrolling to bottom");
container.scrollTop = container.scrollHeight;
}
});
});
observer.observe(container, { childList: true });Watching for Attribute Changes
Reacting when a specific attribute changes on an element.
const target = document.querySelector("#statusBadge");
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
if (mutation.attributeName === "class") {
console.log("Class changed to:", target.className);
}
});
});
observer.observe(target, { attributes: true });
// Stop watching when no longer needed
// observer.disconnect();Best practices
- Use MutationObserver only when you genuinely need to react to DOM changes you do not control directly - if you control the code making the change, call your reaction logic directly instead
- Always call disconnect() when done observing, to avoid unnecessary background processing
- Be specific with the options object (childList, attributes, subtree) rather than observing everything, for better performance
- Avoid triggering more DOM mutations synchronously inside the callback in a way that could create an infinite mutation loop
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification