0

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??

Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166

3 Answers3

3

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>
Community
  • 1
  • 1
Samuel Reid
  • 1,756
  • 12
  • 22
1

Use a conditional callback.

function addJunk(junkToAdd, callback){
    $("#myList").append("<li>"+junkToAdd+"</li>");
    if("function"===typeof callback) callback();
}

addJunk("junk");
addJunk("stuff");

// but this time i wanna do stuff afterwords
addJunk("things", function(){
    alert("just did some stuff");
});
  
addJunk("items");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id='myList'></ol>

Alternatively, you can look into promises.

function addJunk(junkToAdd){
    return new Promise(function(callback){
        $("#myList").append("<li>"+junkToAdd+"</li>");
        callback();
    });
}

addJunk("junk");
addJunk("stuff");

// but this time i wanna do stuff afterwords
addJunk("things").then(function(){
    alert("just did some stuff");
});
  
addJunk("items");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id='myList'></ol>
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
0

In this events reference, I've found there was a DOMNodeInserted event, but it got deprecated. Looks like they're recommending to use Mutation Observers now - there're some examples here, but I've never tried it. Pay attention to the browser compatibility too.

Think twice if you're not overthinking something which is not really need, it could simply just call a function whenever you'd like.

giovannipds
  • 2,860
  • 2
  • 31
  • 39