Use MutationObserver to detect DOM changes
MutationObserver
is a standard solution to the long-standing problem of reacting to DOM changes. Before that, you could use polling among a few other hackish approaches, but they were all problematic in some ways.
And the best part?
All current browsers support it.
Why detect DOM changes?
If you write an app from scratch, you know the places that manipulate the DOM and could add some logic there. But in some cases, for example, if you are writing a framework, you don't know how users will do it.
The textbook example is an undo/redo functionality for a rich text editor. Many plugins can manipulate what's inside the text area, but the undo/redo should work regardless of them supporting it or not.
Get events for mutations
To get notifications for any changes to an element, create a new MutationObserver
and observe
the element:
new MutationObserver(() => {
// DOM changed
}).observe(element, {
childList: true,
attributes: true,
subtree: true,
characterData: true
});
The second argument of observe
is a config. For all the properties that you can set, refer to this article.
The example above listens to all changes that could occur in the element
's the DOM tree.
Disconnect
If the element is removed from the DOM, the MutationObserver
is deleted automatically. Most of the time this alone should prevent any leaks. But in cases where you need to disconnect manually, use .disconnect()
of the MutationObserver
object.