MutationObserver

MutationObserver

Creates a new MutationObserver that watches for changes being made to the DOM tree

Syntax

JavaScript
new MutationObserver(callback)

Parameters

ParameterTypeDescription
callback(mutations: MutationRecord[], observer: MutationObserver) => voidFunction called when DOM changes occur

Return Value

A new MutationObserver instance

Examples

Basic Usage
const observer = new MutationObserver((mutations) => {
  mutations.forEach(m => console.log(m.type, m.target))
})
observer.observe(document.body, { childList: true, subtree: true })
Practical Example
const target = document.getElementById('list')!
const observer = new MutationObserver((mutations) => {
  for (const mutation of mutations) {
    mutation.addedNodes.forEach(node => {
      console.log('Added:', (node as HTMLElement).textContent)
    })
  }
})
observer.observe(target, { childList: true })
Advanced Usage
function watchAttribute(el: Element, attr: string, callback: (old: string | null, val: string | null) => void) {
  const obs = new MutationObserver((muts) => {
    for (const m of muts) {
      callback(m.oldValue, el.getAttribute(attr))
    }
  })
  obs.observe(el, { attributes: true, attributeFilter: [attr], attributeOldValue: true })
  return () => obs.disconnect()
}

Understanding MutationObserver

The MutationObserver method in JavaScript creates a new MutationObserver that watches for changes being made to the DOM tree. It belongs to the MutationObserver object and is one of the most widely used methods for working with mutationobserver values in modern JavaScript and TypeScript applications.

The method signature is new MutationObserver(callback). It accepts 1 parameter: callback. When called, it returns a new mutationobserver instance. Understanding when and how to use MutationObserver() helps you write more expressive, readable code.

Common use cases for MutationObserver include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like event-intersectionobserver, event-resizeobserver, event-addeventlistener, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for MutationObserver is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

Related Tools

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.