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??
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>
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>
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.