My application has some MutationObservers attached to DOM elements low down in the DOM tree. They need to detect when any one of their ancestors are removed from the DOM.
It's simple to use MutationObservers to detect if a particular element or any of its children are removed. However, what is the best way to determine if any of an elements parents are removed?
Here is a plunker that demonstrates the issue. In the plunker, notice that when you click "Remove Parent", the parent element's mutation observer is invoked. However, the child element's observer is not.
How can I efficiently use MutationObservers to check when a node is removed from the document?
Edit
My use case is that I have implemented some web components that need to invoke clean up code when they (or one of their parents) are removed from the DOM. I want each web component to be encapsulated so that it handles its own clean up and there is no global registry (other than the native window.customElements
).
As your implementing your web components from scratch, you should use the native lifecycle callbacks. In your case, the disconnectedCallback
would be the one to trigger your clean up code inside the component.