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?
The actual answer is "use mutation observers" (as outlined in this question: Determining if a HTML element has been added to the DOM dynamically), however support (specifically on IE) is limited (http://caniuse.com/mutationobserver). So the actual ACTUAL answer is "Use mutation observers....
To check if an element is connected or attached to the DOM or the document object ( or otherwise called the context ), you can use the isConnected property in the element's object in JavaScript. The isConnected element property returns boolean true if it connected to the DOM ( document object) and false if not.
The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With