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?
-
Possible duplicate of Event when element added to pageHeretic Monkey– Heretic Monkey2019-01-25 17:36:26 +00:00Commented Jan 25, 2019 at 17:36
-
Does this answer your question? Determining if a HTML element has been added to the DOM dynamicallymiken32– miken322023-12-04 16:05:01 +00:00Commented Dec 4, 2023 at 16:05
4 Answers
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 });
8 Comments
isConnected prop on HTMLElements makes this a little nicer. var x = new MutationObserver(() => { console.log(element.isConnected) }); x.observe(element.parentElement, { childList: true });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');
});
5 Comments
DOMNodeInserted or DOMNodeRemoved, function() { etc.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.
1 Comment
You should bind DOMSubtreeModified event
$("#parent").bind("DOMSubtreeModified",function(){
console.log('changed');
});