Trying Out MutationObservers

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

Thumbnail
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 Codepen.io
Copyright FarhanSharif ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

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

<body>

  <ul id="list">
  
</ul>
  
  

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




</body>

</html>

/*Downloaded from https://www.codeseek.co/FarhanSharif/trying-out-mutationobservers-YaBmGw */
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
  
  
});

Comments