Disconnect Mutation Observer from Callback Function

How can I disconnect my mutation observer from its callback function? The changes are being observed as they should, but I would like to disconnect the observer after the first change. Since the observer variable is out of scope, it's not disconnecting as it should. How can I pass the observer variable to the callback function so the code will work?

function mutate(mutations) {
  mutations.forEach(function(mutation) {
    if ( mutation.type === 'characterData' ) {
      console.log('1st change.');
      observer.disconnect(); // Should disconnect here but observer variable is not defined.
    else if ( mutation.type === 'childList' ) {
      console.log('2nd change. This should not trigger after being disconnected.');

jQuery(document).ready(function() {
  setTimeout(function() {
    document.querySelector('div#mainContainer p').innerHTML = 'Some other text.';
  }, 2000);

  setTimeout(function() {
    jQuery('div#mainContainer').append('<div class="insertedDiv">New div!<//div>');
  }, 4000);

  var targetOne = document.querySelector('div#mainContainer');
  var observer = new MutationObserver( mutate );
  var config = { attributes: true, characterData: true, childList: true, subtree: true };

  observer.observe(targetOne, config);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div id="mainContainer">



The easiest way would be to adjust your callback

function mutate(mutations) {


function mutate(mutations, observer) {

because the observer instance associated with the mutations is automatically passed as the second parameter to the mutation handler function.

Then you can call observer.disconnect() at whichever time you need it.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.