When to Use
- Monitoring a third-party widget for inserted nodes.
- Implementing custom polyfills or custom elements.
- Tracking text changes inside contenteditable elements.
When NOT to Use
- When React or Vue state could just be used instead.
- When you just need to know if an element entered the viewport (use IntersectionObserver).
Code Examples
Good: Observing a specific container
Observes only the specific container and disconnects later.
const target = document.getElementById('my-list');
const observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
}
}
});
observer.observe(target, { childList: true });