Trying Out MutationObservers

In this example below you will see how to do a Trying Out MutationObservers with some HTML / CSS and Javascript

This awesome code was written by FarhanSharif, you can see more from this user in the personal repository.
You can find the original code on
Copyright FarhanSharif ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

  <meta charset="UTF-8">
  <title>Trying Out MutationObservers</title>


  <ul id="list">

    <script  src="js/index.js"></script>



/*Downloaded from */
window.addEventListener("load", function(){
  var list = document.getElementById("list");
  var config = {"childList": true};
  // Callback function when mutation observed
  var callback = function(mutationsList) {
    console.dir(mutationsList); // see what mutationsList is
    console.log("Child added"); // since only adding children
    console.dir(document.getElementById('2')); // see if li#2 is found (it is!)
    document.getElementById('2').style.color = 'red'; // change li#2 to red
    document.getElementById('3').style.fontWeight = 'bold'; // change li#3 to bold
  // observer instance, linked to callback
  var observer = new MutationObserver(callback);
  // start observing
  observer.observe(list, config);
  var listItems = "";
  for (i = 0; i < 6; i++) {
    listItems = listItems + "<li id="+i+"> Item " + i + "</li>";
  list.innerHTML = listItems;
  list.innerHTML = listItems;
  list.innerHTML = listItems;
  // Will only look changes/addition of children elements