jQuery: detecting new elements with the MutationObserver object

jQuery: detecting new elements with the MutationObserver object

How to detect the insertion of new elements with the MutationObserver object in jQuery.

A common problem in JavaScript and jQuery regards the insertion of new elements: how can we detect when a new element has been inserted into the document?

The insertion of new elements that we don't know in advance could be controlled in the past through the DOMNodeInserted event:


$( document ).on( "DOMNodeInserted", function( e ) {
	console.log( e.target );  // the new element	
});

But "this feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped". (– Mozilla documentation). In this case we should use the MutationObserver object.

For example, to monitor an element we can now write:


// The node to be monitored
var target = $( "#content" )[0];

// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
  mutations.forEach(function( mutation ) {
    var newNodes = mutation.addedNodes; // DOM NodeList
    if( newNodes !== null ) { // If there are new nodes added
    	var $nodes = $( newNodes ); // jQuery set
    	$nodes.each(function() {
    		var $node = $( this );
    		if( $node.hasClass( "message" ) ) {
    			// do something
    		}
    	});
    }
  });    
});

// Configuration of the observer:
var config = { 
	attributes: true, 
	childList: true, 
	characterData: true 
};
 
// Pass in the target node, as well as the observer options
observer.observe(target, config);
 
// Later, you can stop observing
observer.disconnect();

As you can see, this is a very effective way of monitoring the insertion of new elements into the DOM.