Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 798
Derek Avatar asked Nov 22 '13 23:11

Derek


People also ask

Which method is triggered when element is added to DOM?

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....

How do you know if an element is attached to DOM?

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.

What is the best way to locate an element in the DOM?

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.


1 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 }); 
like image 183
Qantas 94 Heavy Avatar answered Sep 22 '22 12:09

Qantas 94 Heavy