1

According the to jQuery documentation page, the .change() method calls a handler function whenever the value of the element in question changes. However, this method is limited to <input>, <textarea>, and <select> elements.

How can I do this same thing for <p> elements (and other elements) when their innerHTML changes? It would be nice to find a simple jQuery function that did exactly this.

JCollier
  • 1,102
  • 2
  • 19
  • 31
  • Do none of them answer your question (e.g. [this one](https://stackoverflow.com/questions/1091661/detect-element-content-changes-with-jquery#answer-9328616))? Or are you wondering whether there's a more modern method? – showdev Mar 28 '18 at 18:08
  • 1
    @Kyle solved my problem at [the question](https://stackoverflow.com/questions/1091661/detect-element-content-changes-with-jquery) you mentioned. But none of the answers there answered my specific question, and I am wondering if there is a more modern method, especially if that method includes a very simple jQuery call. – JCollier Mar 28 '18 at 18:37

1 Answers1

2

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

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

// 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();

Here is also library for jQuery : https://github.com/joelpurra/jquery-mutation-summary

// Use document to listen to all events on the page (you might want to be more specific)
var $observerSummaryRoot = $(document);

// Simplest callback, just logging to the console
function callback(summaries){
    console.log(summaries);
}

// Connect mutation-summary
$observerSummaryRoot.mutationSummary("connect", callback, [{ all: true }]);
Iris
  • 1,436
  • 3
  • 14
  • 29