jQuery Event : Detect changes to the html/text of a div

JqueryJquery Ui

Jquery Problem Overview


I have a div which has its content changing all the time , be it ajax requests, jquery functions, blur etc etc.

Is there a way I can detect any changes on my div at any point in time ?

I dont want to use any intervals or default value checked.

Something like this would do

$('mydiv').contentchanged() {
 alert('changed')
}

Jquery Solutions


Solution 1 - Jquery

If you don't want use timer and check innerHTML you can try this event

$('mydiv').on('DOMSubtreeModified', function(){
  console.log('changed');
});

More details and browser support datas are Here.

Solution 2 - Jquery

Using Javascript MutationObserver:

// Select the target node.
var target = document.querySelector('mydiv')

// Create an observer instance.
var observer = new MutationObserver(function(mutations) {
    console.log(target.innerText);   
});

// Pass in the target node, as well as the observer options.
observer.observe(target, {
	attributes:    true,
	childList:     true,
	characterData: true
});

See the MDN documentation for details; this should work in pretty much all current browser, including IE11.

Solution 3 - Jquery

Since $("#selector").bind() is deprecated, you should use:

$("body").on('DOMSubtreeModified', "#selector", function() {
    // code here
});

Solution 4 - Jquery

You can try this

$('.myDiv').bind('DOMNodeInserted DOMNodeRemoved', function() {
    
});

but this might not work in internet explorer, haven't tested it

Solution 5 - Jquery

You are looking for MutationObserver or Mutation Events. Neither are supported everywhere nor are looked upon too fondly by the developer world.

If you know (and can make sure that) the div's size will change, you may be able to use the crossbrowser resize event.

Solution 6 - Jquery

The following code works for me:

$("body").on('DOMSubtreeModified', "mydiv", function() {
    alert('changed');
});

Solution 7 - Jquery

There is no inbuilt solution to this problem, this is a problem with your design and coding pattern.

You can use publisher/subscriber pattern. For this you can use jQuery custom events or your own event mechanism.

First,

function changeHtml(selector, html) {
    var elem = $(selector);
    jQuery.event.trigger('htmlchanging', { elements: elem, content: { current: elem.html(), pending: html} });
    elem.html(html);
    jQuery.event.trigger('htmlchanged', { elements: elem, content: html });
}

Now you can subscribe divhtmlchanging/divhtmlchanged events as follow,

$(document).bind('htmlchanging', function (e, data) {
    //your before changing html, logic goes here
});

$(document).bind('htmlchanged', function (e, data) {
    //your after changed html, logic goes here
});

Now, you have to change your div content changes through this changeHtml() function. So, you can monitor or can do necessary changes accordingly because bind callback data argument containing the information.

You have to change your div's html like this;

changeHtml('#mydiv', '<p>test content</p>');

And also, you can use this for any html element(s) except input element. Anyway you can modify this to use with any element(s).

Solution 8 - Jquery

Use MutationObserver as seen in this snippet provided by Mozilla, and adapted from this blog post

Alternatively, you can use the JQuery example seen in this link

Chrome 18+, Firefox 14+, IE 11+, Safari 6+

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

Solution 9 - Jquery

Tried some of answers given above but those fires event twice. Here is working solution if you may need the same.

$('mydiv').one('DOMSubtreeModified', function(){
    console.log('changed');
});

Solution 10 - Jquery

You can store the old innerHTML of the div in a variable. Set an interval to check if the old content matches the current content. When this isn't true do something.

Solution 11 - Jquery

Try the MutationObserver:

browser support: http://caniuse.com/#feat=mutationobserver

<html>
  <!-- example from Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/dom/mutation-observers/ -->

  <head>
    </head>
  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript">
      // Inspect the array of MutationRecord objects to identify the nature of the change
function mutationObjectCallback(mutationRecordsList) {
  console.log("mutationObjectCallback invoked.");

  mutationRecordsList.forEach(function(mutationRecord) {
    console.log("Type of mutation: " + mutationRecord.type);
    if ("attributes" === mutationRecord.type) {
      console.log("Old attribute value: " + mutationRecord.oldValue);
    }
  });
}
      
// Create an observer object and assign a callback function
var observerObject = new MutationObserver(mutationObjectCallback);

      // the target to watch, this could be #yourUniqueDiv 
      // we use the body to watch for changes
var targetObject = document.body; 
      
// Register the target node to observe and specify which DOM changes to watch
      
      
observerObject.observe(targetObject, { 
  attributes: true,
  attributeFilter: ["id", "dir"],
  attributeOldValue: true,
  childList: true
});

// This will invoke the mutationObjectCallback function (but only after all script in this
// scope has run). For now, it simply queues a MutationRecord object with the change information
targetObject.appendChild(document.createElement('div'));

// Now a second MutationRecord object will be added, this time for an attribute change
targetObject.dir = 'rtl';


      </script>
    </body>
  </html>

Solution 12 - Jquery

DOMSubtreeModified is not a good solution. It can cause infinite loops if you decide to change the DOM inside the event handler, hence it has been disabled in a number of browsers. MutationObserver is the better answer.

MDN Doc

const onChangeElement = (qSelector, cb)=>{
 const targetNode = document.querySelector(qSelector);
 if(targetNode){
    const config = { attributes: true, childList: false, subtree: false };
    const callback = function(mutationsList, observer) {
        cb($(qSelector))
    };
    const observer = new MutationObserver(callback);
    observer.observe(targetNode, config);
 }else {
    console.error("onChangeElement: Invalid Selector")
 }
}

And you can use it like,

onChangeElement('mydiv', function(jqueryElement){
   alert('changed')
})

Solution 13 - Jquery

Adding some content to a div, whether through jQuery or via de DOM-API directly, defaults to the .appendChild() function. What you can do is to override the .appendChild() function of the current object and implement an observer in it. Now having overridden our .appendChild() function, we need to borrow that function from an other object to be able to append the content. Therefor we call the .appendChild() of an other div to finally append the content. Ofcourse, this counts also for the .removeChild().

var obj = document.getElementById("mydiv");
    obj.appendChild = function(node) {
        alert("changed!");

        // call the .appendChild() function of some other div
        // and pass the current (this) to let the function affect it.
        document.createElement("div").appendChild.call(this, node);
        }
    };

Here you can find a naïf example. You can extend it by yourself I guess. http://jsfiddle.net/RKLmA/31/

By the way: this shows JavaScript complies the OpenClosed priciple. :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBoqBoqView Question on Stackoverflow
Solution 1 - JqueryimanView Answer on Stackoverflow
Solution 2 - JqueryPPBView Answer on Stackoverflow
Solution 3 - JqueryPetar NikovView Answer on Stackoverflow
Solution 4 - Jqueryuser1790464View Answer on Stackoverflow
Solution 5 - JqueryrodneyrehmView Answer on Stackoverflow
Solution 6 - JquerySanchit GuptaView Answer on Stackoverflow
Solution 7 - JquerySaminatorMView Answer on Stackoverflow
Solution 8 - JqueryAnthony AwuleyView Answer on Stackoverflow
Solution 9 - JqueryVirang JethvaView Answer on Stackoverflow
Solution 10 - JquerycodeloveView Answer on Stackoverflow
Solution 11 - JqueryjuFoView Answer on Stackoverflow
Solution 12 - JqueryRuwan MadusankaView Answer on Stackoverflow
Solution 13 - JqueryAndriesView Answer on Stackoverflow