MutationObserver

  • Revision slug: DOM/MutationObserver
  • Revision title: MutationObserver
  • Revision id: 347199
  • Created:
  • Creator: Brettz9
  • Is current revision? No
  • Comment +;

Revision Content

MutationObserver provides developers a way to react to changes in a DOM. It is designed as a replacement for Mutation Events defined in the DOM3 Events specification.

Constructor

MutationObserver()

Constructor for instantiating new DOM mutation observers.

MutationObserver(
  function callback
);
Parameters
callback
The function which will be called on each DOM mutation. The observer will call this function with two arguments. The first is an array of objects, each of type MutationRecord. The second is this MutationObserver instance.

Instance methods

void observe( {{domxref("Node")}} target, optional MutationObserverInit options );
void disconnect();
Array takeRecords();

observe()

Registers the MutationObserver instance to receive notifications of DOM mutations on the specified node.

void observe(
  {{domxref("Node")}} target,
  optional MutationObserverInit options
);
Parameters
target
The {{domxref("Node")}} on which to observe DOM mutations.
options
A MutationObserverInit object, specifies which DOM mutations should be reported.

disconnect()

Stops the MutationObserver instance from receiving notifications of DOM mutations. Until the observe() method is used again, observer's callback will not be invoked.

void disconnect();

takeRecords()

Empties the MutationObserver instance's record queue and returns what was in there.

Array takeRecords();
Return value

Returns an Array of MutationRecords.

MutationObserverInit

MutationObserverInit is an object which can specify the following properties:

NOTE: At the very least, childList, attributes, or characterData must be set to true. Otherwise, "An invalid or illegal string was specified" error is thrown.
Property Description
childList Set to true if mutations to target's children are to be observed.
attributes Set to true if mutations to target's attributes are to be observed.
characterData Set to true if mutations to target's data are to be observed.
subtree Set to true if mutations to not just target, but also target's descendants are to be observed.
attributeOldValue Set to true if attributes is set to true and target's attribute value before the mutation needs to be recorded.
characterDataOldValue Set to true if characterData is set to true and target's data before the mutation needs to be recorded.
attributeFilter Set to an array of attribute local names (without namespace) if not all attribute mutations need to be observed.

MutationRecord

MutationRecord is the object that will be passed to the observer's callback. It has the following properties:

Property Type Description
type String Returns attributes if it was an attribute mutation. characterData if it was a mutation to a CharacterData node. And childList if it was a mutation to the tree of nodes.
target {{domxref("Node")}} Returns the node the mutation affected, depending on the type. For attributes, it is the element whose attribute changed. For characterData, it is the CharacterData node. For childList, it is the node whose children changed.
addedNodes {{domxref("NodeList")}} Return the nodes added, or null.
removedNodes {{domxref("NodeList")}} Return the nodes removed, or null.
previousSibling {{domxref("Node")}} Return the previous sibling of the added or removed nodes, or null.
nextSibling {{domxref("Node")}} Return the next sibling of the added or removed nodes, or null.
attributeName String Returns the local name of the changed attribute, or null.
attributeNamespace String Returns the namespace of the changed attribute, or null.
oldValue String The return value depends on the type. For attributes, it is the value of the changed attribute before the change. For characterData, it is the data of the changed node before the change. For childList, it is null.

Example usage

The following example was taken from this blog post.

// select the target node
var target = document.querySelector('#some-id');
 
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});
 
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
 
// pass in the target node, as well as the observer options
observer.observe(target, config);
 
// later, you can stop observing
observer.disconnect();

Additional reading

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{ CompatVersionUnknown() }} {{ property_prefix("webkit") }} {{ CompatGeckoDesktop(14) }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatGeckoMobile(14) }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}

 

Revision Source

<p><code>MutationObserver</code> provides developers a way to react to changes in a <a href="/en-US/docs/DOM">DOM</a>. It is designed as a replacement for <a href="/en-US/docs/DOM/Mutation_events">Mutation Events</a> defined in the DOM3 Events specification.</p>
<h2 id="Constructor" name="Constructor">Constructor</h2>
<h3 id="MutationObserver()" name="MutationObserver()"><code>MutationObserver()</code></h3>
<p>Constructor for instantiating new DOM mutation observers.</p>
<pre class="eval">MutationObserver(
  function callback
);
</pre>
<h6 id="Parameters" name="Parameters">Parameters</h6>
<dl>
  <dt>
    <code>callback</code></dt>
  <dd>
    The function which will be called on each DOM mutation. The observer will call this function with two arguments. The first is an array of objects, each of type <a href="#MutationRecord"><code>MutationRecord</code></a>. The second is this <code>MutationObserver</code> instance.</dd>
</dl>
<h2 id="Instance_methods" name="Instance_methods">Instance methods</h2>
<table class="standard-table">
  <tbody>
    <tr>
      <td><code>void <a href="#observe()">observe</a>( {{domxref("Node")}} target, optional <a href="#MutationObserverInit">MutationObserverInit</a> options );</code></td>
    </tr>
    <tr>
      <td><code>void <a href="#disconnect()">disconnect</a>();</code></td>
    </tr>
    <tr>
      <td><code>Array <a href="#takeRecords()">takeRecords</a>();</code></td>
    </tr>
  </tbody>
</table>
<h3 id="observe()" name="observe()"><code>observe()</code></h3>
<p>Registers the <code>MutationObserver</code> instance to receive notifications of DOM mutations on the specified node.</p>
<pre class="eval">void observe(
  {{domxref("Node")}} target,
  optional <a href="#MutationObserverInit"><code>MutationObserverInit</code></a> options
);
</pre>
<h6 id="Parameters" name="Parameters">Parameters</h6>
<dl>
  <dt>
    <code>target</code></dt>
  <dd>
    The {{domxref("Node")}} on which to observe DOM mutations.</dd>
  <dt>
    <code>options</code></dt>
  <dd>
    A <a href="#MutationObserverInit"><code>MutationObserverInit</code></a> object, specifies which DOM mutations should be reported.</dd>
</dl>
<h3 id="disconnect()" name="disconnect()"><code>disconnect()</code></h3>
<p>Stops the <code>MutationObserver</code> instance from receiving notifications of DOM mutations. Until the <a href="#observe()"><code>observe()</code></a> method is used again, observer's callback will not be invoked.</p>
<pre class="eval">void disconnect();
</pre>
<h3 id="takeRecords()" name="takeRecords()"><code>takeRecords()</code></h3>
<p>Empties the <code>MutationObserver</code> instance's record queue and returns what was in there.</p>
<pre class="eval">Array takeRecords();
</pre>
<h6 id="Return_value" name="Return_value">Return value</h6>
<p>Returns an Array of <a href="#MutationRecord"><code>MutationRecord</code>s</a>.</p>
<h2 id="MutationObserverInit" name="MutationObserverInit"><code>MutationObserverInit</code></h2>
<p><code>MutationObserverInit</code> is an object which can specify the following properties:</p>
<div class="note">
  NOTE: At the very least, <code>childList</code>, <code>attributes</code>, or <code>characterData</code> must be set to <code>true</code>. Otherwise, "An invalid or illegal string was specified" error is thrown.</div>
<table class="standard-table">
  <tbody>
    <tr>
      <td class="header">Property</td>
      <td class="header">Description</td>
    </tr>
    <tr>
      <td><code>childList</code></td>
      <td>Set to <code>true</code> if mutations to target's children are to be observed.</td>
    </tr>
    <tr>
      <td><code>attributes</code></td>
      <td>Set to <code>true</code> if mutations to target's attributes are to be observed.</td>
    </tr>
    <tr>
      <td><code>characterData</code></td>
      <td>Set to <code>true</code> if mutations to target's data are to be observed.</td>
    </tr>
    <tr>
      <td><code>subtree</code></td>
      <td>Set to <code>true</code> if mutations to not just target, but also target's descendants are to be observed.</td>
    </tr>
    <tr>
      <td><code>attributeOldValue</code></td>
      <td>Set to <code>true</code> if <code>attributes</code> is set to <code>true</code> and target's attribute value before the mutation needs to be recorded.</td>
    </tr>
    <tr>
      <td><code>characterDataOldValue</code></td>
      <td>Set to <code>true</code> if <code>characterData</code> is set to <code>true</code> and target's data before the mutation needs to be recorded.</td>
    </tr>
    <tr>
      <td><code>attributeFilter</code></td>
      <td>Set to an array of attribute local names (without namespace) if not all attribute mutations need to be observed.</td>
    </tr>
  </tbody>
</table>
<h2 id="MutationRecord" name="MutationRecord"><code>MutationRecord</code></h2>
<p><code>MutationRecord</code> is the object that will be passed to the observer's callback. It has the following properties:</p>
<table class="standard-table">
  <tbody>
    <tr>
      <td class="header">Property</td>
      <td class="header">Type</td>
      <td class="header">Description</td>
    </tr>
    <tr>
      <td><code>type</code></td>
      <td><code>String</code></td>
      <td>Returns <code>attributes</code> if it was an attribute mutation. <code>characterData</code> if it was a mutation to a <code>CharacterData</code> node. And <code>childList</code> if it was a mutation to the tree of nodes.</td>
    </tr>
    <tr>
      <td><code>target</code></td>
      <td><code>{{domxref("Node")}}</code></td>
      <td>Returns the node the mutation affected, depending on the <code>type</code>. For <code>attributes</code>, it is the element whose attribute changed. For <code>characterData</code>, it is the <code>CharacterData</code> node. For <code>childList</code>, it is the node whose children changed.</td>
    </tr>
    <tr>
      <td><code>addedNodes</code></td>
      <td><code>{{domxref("NodeList")}}</code></td>
      <td>Return the nodes added, or <code>null</code>.</td>
    </tr>
    <tr>
      <td><code>removedNodes</code></td>
      <td><code>{{domxref("NodeList")}}</code></td>
      <td>Return the nodes removed, or <code>null</code>.</td>
    </tr>
    <tr>
      <td><code>previousSibling</code></td>
      <td><code>{{domxref("Node")}}</code></td>
      <td>Return the previous sibling of the added or removed nodes, or <code>null</code>.</td>
    </tr>
    <tr>
      <td><code>nextSibling</code></td>
      <td><code>{{domxref("Node")}}</code></td>
      <td>Return the next sibling of the added or removed nodes, or <code>null</code>.</td>
    </tr>
    <tr>
      <td><code>attributeName</code></td>
      <td><code>String</code></td>
      <td>Returns the local name of the changed attribute, or <code>null</code>.</td>
    </tr>
    <tr>
      <td><code>attributeNamespace</code></td>
      <td><code>String</code></td>
      <td>Returns the namespace of the changed attribute, or <code>null</code>.</td>
    </tr>
    <tr>
      <td><code>oldValue</code></td>
      <td><code>String</code></td>
      <td>The return value depends on the <code>type</code>. For <code>attributes</code>, it is the value of the changed attribute before the change. For <code>characterData</code>, it is the data of the changed node before the change. For <code>childList</code>, it is <code>null</code>.</td>
    </tr>
  </tbody>
</table>
<h2 id="Example_usage" name="Example_usage">Example usage</h2>
<p>The following example was taken from <a class="external" href="http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/" rel="freelink">this blog post</a>.</p>
<pre class="brush: js">// select the target node
var target = document.querySelector('#some-id');
 
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});
 
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
 
// pass in the target node, as well as the observer options
observer.observe(target, config);
 
// later, you can stop observing
observer.disconnect();
</pre>
<h2 id="Additional_reading" name="Additional_reading">Additional reading</h2>
<ul>
  <li><a class="external" href="http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers" rel="freelink">A brief overview</a></li>
  <li><a class="external" href="http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/" rel="freelink">A more in-depth discussion</a></li>
  <li><a class="external" href="http://www.youtube.com/watch?v=eRZ4pO0gVWw" rel="freelink">A screencast by Chromium developer Rafael Weinstein</a></li>
  <li><a class="external" href="http://code.google.com/p/mutation-summary/" rel="freelink">The mutation summary library</a></li>
  <li><a class="external" href="http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#mutation-observers" rel="freelink">The DOM4 specification</a> which defines the <code>MutationObserver</code> interface</li>
</ul>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Chrome</th>
        <th>Firefox (Gecko)</th>
        <th>Internet Explorer</th>
        <th>Opera</th>
        <th>Safari</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{ CompatVersionUnknown() }} {{ property_prefix("webkit") }}</td>
        <td>{{ CompatGeckoDesktop(14) }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
      </tr>
    </tbody>
  </table>
</div>
<div id="compat-mobile">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Android</th>
        <th>Chrome for Android</th>
        <th>Firefox Mobile (Gecko)</th>
        <th>IE Mobile</th>
        <th>Opera Mobile</th>
        <th>Safari Mobile</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatGeckoMobile(14) }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
      </tr>
    </tbody>
  </table>
</div>
<p> </p>
Revert to this revision