Skip to main content

Observe Changes in DOM using Mutation Observers

In our previous tutorial, we have explained how to convert CSV data to JSON with JavaScript. In this tutorial, you will learn how to Observe Changes in DOM using Mutation Observers in JavaScript when any element added, removed or attribute changed in DOM.

While loading dynamic data with Ajax, we append data with new HTML elements to already loaded HTML page. As the dynamic data HTML appended after DOM load, the existing front-end functionality will not work with new appended HTML element because the specific functions not initialize that new elements.

So we need to detect newly added DOM elements related to that specific functions and then we need to initialize that elements. If you’re struck with such problems and looking for solutions, then you’re here at right place.

The MutationObserver is a JavaScript browser API to detect DOM changes and it’s supported by all modern browsers. We will cover this tutorial with live demo to add dynamic element with attributes to page and then detect newly added element using MutationObserver API API.

Also, read:

So let’s create example to Observe Changes in DOM using Mutation Observers In JavaScript. The file structure of this example is following.

  • index.php
  • mutation_observer.js

Step1: Create HTML to Add New Element

First we will create HTML in index.php to add dynamic element to page.

<div class="container">
<h2>Example: Detect DOM Change using Mutation Observer with Example</h2>		
<div id="containerBody" class="well well-sm message">Click Add Element button to add new element to DOM.</div>
<div><span id="labelID" class="hidden"><strong>New element added to DOM with ID: </strong></span><span id="addNodeId"></span></div>
<div><span id="labelClass" class="hidden"><strong>New element added to DOM with classes: </strong></span><span id="addNodeClass"></span></div>
<button id="addElement" class="btn btn-primary">Add element</button>    
</div>
Step2: Add Dynamic Element to Page

Now in mutation_observer.js file, we will add dynamic element to page with class and id attribute when click button.

$("#addElement").click(function() {
	var totalElement = $(".message").length;
	$("#containerBody").after("<div id='message_"+totalElement+"' class='well well-sm message'>This is a new element added to DOM.</div>");
});

Step3: Detect Changes in DOM with MutationObserver

In mutation_observer.js file, we will use MutationObserver instance to detect DOM changes. Here we will check for class message to detect if it is added to DOM and display newly added element id and clss attribute. We can handle our functions here according to our requirement to work with dynamic HTML that’s added to page after DOM load. We have checked here mutations addedNodes attribute to check for new node. You can use removedNodes to check for element remove.

// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
	mutations.forEach(function( mutation ) {		
		var newNodes = mutation.addedNodes; 
		// If there are new nodes added
		if( newNodes !== null ) { 
			var $nodes = $( newNodes ); 
			$nodes.each(function() {
				var $node = $( this );
				// check if new node added with class 'message'
				if( $node.hasClass("message")){			
					$("#addNodeId").text($($node).attr('id'));
					$("#addNodeClass").text($($node).attr('class'));
				}
			});
		}
	});    
});
// Configuration of the observer:
var config = { 
	childList: true,
	attributes: true,
	subtree: true,
	characterData: true
}; 
var targetNode = document.body;
observer.observe(targetNode, config);

You may also like:

You can view the live demo from the Demo link and can download the source from the Download link below.
Demo Download