There is new HTML5 API called MutationObserver that allow to add events when DOM is changing including a case when element is added or removed from DOM. Mutation observer support is pretty good.
Here is example to detect if element is added/removed from DOM:
var in_dom = document.body.contains(element); var observer = new MutationObserver(function(mutations) { if (document.body.contains(element)) { if (!in_dom) { console.log("element inserted"); } in_dom = true; } else if (in_dom) { in_dom = false; console.log("element removed"); } }); observer.observe(document.body, {childList: true});
to stop listening to changes you can run:
observer.disconnect();
The sample code is a bit confusing. I believe it needs a bit more clear example. Here you can find a good article about MutationObserver: http://blog.piotrnalepa.pl/2015/09/09/js-jak-obserwowac-zmiany-obiektow-w-javascript-natywny-data-binding/
Perfect thanks!
Very helpful, thank you!
nice and simple, I was looking for a solution that will get me ANY element that has been added to the dom, found it thank to this article:
http://straightdeveloper.com/jquery-event-to-detect-any-new-element-in-the-dom/