JavaScript Interview Question #168
What is MutationObserver?
Performance, Browser APIs, Rendering & Modern Web Architecture Senior Advanced
Quick Interview Answer
MutationObserver watches a DOM subtree for configured changes such as child additions/removals, attribute changes, or text mutations. The observer receives mutation records asynchronously.
Detailed Explanation
MutationObserver watches a DOM subtree for configured changes such as child additions/removals, attribute changes, or text mutations. The observer receives mutation records asynchronously.
It is useful when code genuinely needs to react to DOM changes outside its direct control. It should not replace clear application state management when the application itself already knows when it modifies the DOM.
Code Example
const target = document.querySelector("#content");
const observer = new MutationObserver(records => {
for (const record of records) {
console.log(record.type);
}
});
observer.observe(target, {
childList: true,
subtree: true
});