Javascript / jQuery : Handling dynamic text change inside HTML elements with Example

To detect the event when text change inside the any HTML element like div, span, table or etc., using DOMNodeInserted, DOMContentLoaded, DOMSubtreeModified and DOMNodeRemoved events. These events are known as Mutation events. Below is the sample code of handling Mutation events on different browsers.

jQuery Event Bind using Mutation:

 

The below is syntax of handling event in jQuery using bind function. In here we specify the Listening HTML element and  Mutation event type.

Syntax:

jQuery("#ElemntID").bind(“DOM EVENT TYPE”, function() {
  // Do your stuff.
  alert(“DOM Event Initiated”);
});
//Event types are DOMNodeInserted, DOMContentLoaded, DOMSubtreeModified and DOMNodeRemoved

Example:

jQuery(“.jquery-countdown-processed").bind(“DOMNodeInserted”, function() {
  alert(“Content change in countdown”);
});

 

Mutation Deprecated in Chrome and IE:

 

Mutation Events deprecated in WebKit and IE browsers. To achieve Mutation event in this type of browsers by creating the Mutation object, this object handle the DOM change events.

Syntax:

EventObserver = window.MutationObserver || window.WebKitMutationObserver;
var handler = new EventObserver(function(mutations, observer) {
   // Do your stuff.
   alert(“DOM Event Initiated”);
});
 
observer.observe(document, {
  subtree: true,
  attributes: true
});

Example:

EventObserver = window.MutationObserver || window.WebKitMutationObserver;
var handler = new EventObserver(function(mutations, observer) {
  if (mutations[0].target.className == "jquery-countdown-processed") {
    alert(“Content change in countdown”);
  }
});
 
observer.observe(document, {
 subtree: true,
 attributes: true
});
Category: