Tomasz Mularczyk Tomasz Mularczyk - 9 months ago 48
HTML Question

Fire up event when element is inserted to html OL

I have a list

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

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

Answer Source

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){
    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>fifth :(</li>
<button onclick="add()">Add</button>