How to detect element being added/removed from dom element?

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?

Answers:

Answer

You should bind DOMSubtreeModified event

$("#parent").bind("DOMSubtreeModified",function(){
  console.log('changed');
});

http://jsfiddle.net/WQeM3/

Answer

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');
});

MDN Docs

Answer

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 });

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.