Tomasz Mularczyk Tomasz Mularczyk - 29 days ago 12
HTML Question

Fire up event when element is inserted to html OL

I have a list

ol
in HTML where I dynamically add new elements after user action.

Is it possible to register a method which will be called after new
li
has been added to list??

Answer

Mutation Observers

Other similar answer: Detect changes in the DOM

The following works in Chrome 18+, Firefox 14+, IE 11+, Opera 15+, and Safari 6+ and is documented here.

function add() {
  document.getElementById("list").innerHTML += "<li>added</li>";
}

// Where listening for new <li>s happens
var observer = new MutationObserver(function(mutations){
  mutations.forEach(function(mutation){
    document.getElementById("output").innerHTML += "Doing something on DOM change.\n";
  });
});

var config = { attributes: true, childList: true, characterData: true };

observer.observe(document.getElementById("list"), config);
<pre id="output"></pre>
<ol id="list">
  <li>First!</li>
  <li>Second.</li>
  <li>Third...</li>
  <li>fourth......</li>
  <li>fifth :(</li>
</ol>
<button onclick="add()">Add</button>