---
title: "DOM Mutation Observers"
description: "Using MutationObserver API to watch for DOM tree changes. Practical notes and code examples on DOM Mutation Observers by."
url: "https://h3manth.com/scribe/dom-mutation-observers/"
canonical_url: "https://h3manth.com/scribe/dom-mutation-observers/"
markdown_url: "https://h3manth.com/scribe/blog/dom-mutation-observers.md"
publishDate: "2013-11-11T00:00:00.000Z"
author: "Hemanth HM"
category: "web"
tags: ["javascript","dom","web-api"]
word_count: 110
reading_time_minutes: 1
x_markdown_tokens: 377
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# DOM Mutation Observers

> Using MutationObserver API to watch for DOM tree changes. Practical notes and code examples on DOM Mutation Observers by.

`MutationObserver` can be used to observe mutations to the tree of nodes. It's designed as a replacement for Mutation Events defined in the DOM3 Events specification.

## API

```javascript
var observer = new MutationObserver(callback);
observer.observe(target, options);  // Observe the desired node
observer.disconnect();              // Stop observing
observer.takeRecords();             // Empty and return the record queue

## Example: Random Image Loader
javascript
var matrix = document.querySelector("#imgs");
var imgServ = [
  "http://lorempizza.com/i/380/240",
  "http://lorempixel.com/380/240/"
];

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    var size = matrix.childElementCount;
    matrix.children[size - 1].src = 
      imgServ[Math.floor(imgServ.length * Math.random())] + 
      "#" + Math.random().toString(36).substring(7);
  });
});

observer.observe(matrix, { childList: true });

setInterval(function() {
  matrix.appendChild(document.createElement('img'));
}, 1000);
```

Don't miss the [spec](https://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#mutation-observers)!
