Observe Node And Attribute Changes In The Document - jQuery Mutation Observe

Observe Node And Attribute Changes In The Document - jQuery Mutation Observe

Mutation Observe is a jQuery plugin which invokes specified callback functions when attributes and/or nodes have been changed in the DOM.

Powered by the Mutation‚ÄčObserver Web API that provides the ability to watch for changes being made to the DOM tree.

1. To get started, include both jQuery library and the Mutation Observe plugin on the web page.

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" 
        integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" 
        crossorigin="anonymous">
</script>
<script src="jquery-mutation-observe.js"></script>

2. Execute a callback when a specific attribute has been changed.

  • data.oldValue: Old value
  • data.newValue: New value
$('.element')
  .observeAttribute({
    'attributes': 'class',
    'callback': function(data){
      log('attribute:class has been changed from ['+data.oldValue+'] to ['+data.newValue+'] on self');
    }
})

3. Execute a callback when a node has been added or removed from the DOM.

$('.element')
  .observeNode({
    'selector': '> .child',
    'callback': function(data) {
      var tag = escapeHtml($(data.node).prop('outerHTML'));
      if (data.type=='add') {
        log('node has been added to a child element directly under self element. <br>tag: ' + tag);
      } else if (data.type=='remove') {
        log('node has been removed from a child element directly under self element. <br>tag:' + tag);
      }
    }
})

This awesome jQuery plugin is developed by takitakit. For more Advanced Usages, please check the demo page or visit the official website.

  • Publication date: 07.05.2019
  • Source