MutationObserver
A browser object that watches part of the DOM and reports changes, such as added nodes or changed attributes, in batches.
In more detail
You call observe(target, options) with options such as childList, attributes, subtree and attributeFilter. Changes are delivered as MutationRecord objects to your callback in a microtask, several at once. Always call disconnect() when you no longer need it, or it keeps the observed nodes alive.
Example
observer.observe(root, { childList: true, attributes: true, attributeFilter: ['data-theme'], subtree: true })Related terms
- mutation events — An old, removed way of watching DOM changes that fired a synchronous event for every single change.
- polling — Having the client ask repeatedly, on its own schedule, whether something has changed or finished.
- microtask — A small job, such as a promise callback, that runs as soon as the current piece of JavaScript finishes, before the event loop handles anything else.
- detached DOM tree — DOM nodes that have been removed from the page but are still kept in memory because some JavaScript still references them.
- memory leak — Memory that a program keeps holding although it no longer needs it, so usage grows until the program slows down or crashes.
Taught in
- MutationObserver: Reactive DOM Watching Without Polling — Frontend Architecture & Web Platform
- Semantic HTML Elements: Landmarks And Structure — Frontend Architecture & Web Platform