How to detect element being added/removed from dom element?
JavascriptJqueryHtmlJavascript Problem Overview
Say I had a div#parent
and I append
and remove
elements to it using jquery. How would I be able to detect when such an event happens on the div#parent
element?
Javascript Solutions
Solution 1 - Javascript
Don't use mutation events like DOMNodeInserted and DOMNodeRemoved.
Instead, use DOM Mutation Observers, which are supported in all modern browsers except IE10 and lower (Can I use). Mutation observers are intended to replace mutation events (which have been deprecated), as they have been found to have low performance due to flaws in its design.
var x = new MutationObserver(function (e) {
if (e[0].removedNodes) console.log(1);
});
x.observe(document.getElementById('parent'), { childList: true });
Solution 2 - Javascript
Use Mutation Observers as suggested by @Qantas in his answer
Following methods are deprecated
You can use DOMNodeInserted and DOMNodeRemoved
$("#parent").on('DOMNodeInserted', function(e) {
console.log(e.target, ' was inserted');
});
$("#parent").on('DOMNodeRemoved', function(e) {
console.log(e.target, ' was removed');
});
Solution 3 - Javascript
You should bind DOMSubtreeModified
event
$("#parent").bind("DOMSubtreeModified",function(){
console.log('changed');
});
Solution 4 - Javascript
It wouldn't let me comment below on the top answer but to answer your question @DenisKolodin, in order to listen for self-destruction, you can do something like this:
function watchElForDeletion(elToWatch, callback, parent = document.querySelector('body')){
const observer = new MutationObserver(function (mutations) {
// loop through all mutations
mutations.forEach(function (mutation) {
// check for changes to the child list
if (mutation.type === 'childList') {
// check if anything was removed and if the specific element we were looking for was removed
if (mutation.removedNodes.length > 0 && mutation.removedNodes[0] === elToWatch) {
callback();
}
}
});
});
// start observing the parent - defaults to document body
observer.observe(parent, { childList: true });
};
It defaults to the parent being the body element and only runs the callback if the specific element you're looking for is deleted.