Mutation Observer in JavaScript

From the DOM Manipulation cheat sheet · Modern DOM APIs · verified Jul 2026

Mutation Observer

Watch for changes to the DOM tree and element attributes

javascript
// Create observer
const observer = new MutationObserver((mutations) => {
  mutations.forEach(mutation => {
    console.log('Type:', mutation.type)
    console.log('Target:', mutation.target)
  })
})

// Observe element
observer.observe(element, {
  childList: true,      // Child changes
  attributes: true,     // Attribute changes
  subtree: true        // All descendants
})

// Stop observing
observer.disconnect()
💡 Can detect any DOM change
⚠️ Be careful with subtree: true on large DOMs
📌 Use takeRecords() to get pending mutations
✅ Always disconnect when no longer needed

More JavaScript tasks

Back to the full DOM Manipulation cheat sheet