iuliu.net iuliu.net - 1 month ago 14
jQuery Question

Detect DOM changes (check for changes in elements order)

I have the following code:

<div>
<span>Random text</span>
<span style="color: red">Random text</span>
</div>


and, using code, I have a 50% chance of changing the order of the elements inside the div.

$(document).ready(function() {
var initial = $("div"); //This might not be ok

if (new Date() % 2) //50% chance to randomize order
randomizeOrder();

var after = $("div"); //Also this might not be ok
//Detect if the order of spans changed
if (after != initial) //Definitely won't work
console.log("Order changed");
})

function randomizeOrder() {
var lastElement = $("div span").last();
$(lastElement).insertBefore($("div span").first());
}


This example is oversimplified. The ordering is done by the user using a 3rd party library which won't tell me if the order actually changed, just tell me when it started & finished.

How can I detect if the order of the DOM elements actually changed? The information I have inside them cannot be used, as it can be exactly the same, as in the example.

Fiddle

Answer

If you want to check for changes in the DOM you can use the MutationObserver:

$(document).ready(function() {
  var initial = $("div"); //This might not be ok

  if (new Date() % 2) {
    randomizeOrder();
  }
  
});

function randomizeOrder() {
  var lastElement = $("div span").last();
  $(lastElement).insertBefore($("div span").first());
}

var target = document.getElementById('id1');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  var changed = false;
  mutations.forEach(function(mutation) {
    // You can check the actual changes here
  });
  console.log('Dom Changed');
});

// 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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1">
  <span>Random text</span> 
  <span style="color: red">Random text</span>
</div>

The MutationObserver gives you the ability to check for DOM changes in a specific element, without any requirement regarding the code the changes the DOM.