Is there any way to get notification when an element is removed from the DOM, either directly or as part of a subtree? It seems like the only methods available are just for directly removed nodes, but I would like to get a notification when a whole subtree that contains my node is removed.
EDIT
Seems the problem wasn't entirely clear, so I have made a challenge: https://jsbin.com/winukaf
The DOM looks like this:
<body>
<div class="root">
<div class="great-grand-parent">
<div class="grand-parent">
<div class="parent">
<div class="leaf">
Am I still here?
</div>
</div>
</div>
</div>
</div>
</body>
and the challenge is to notify when any one of the elements here are removed, since that will remove the leaf node from the DOM tree.
In modern browsers, if a DOM Element is removed, its listeners are also removed from memory in javascript. Note that this will happen ONLY if the element is reference-free. Or in other words, it doesn't have any reference and can be garbage collected. Only then its event listeners will be removed from memory.
We can detect whether an element has been removed DOM using the MutationObserver object. MutationObserver provides the ability to observe for changes being made to the DOM tree.
If you want to remove the element from the DOM entirely, you can use the removeChild() method. var elem = document. querySelector('#some-element'); elem. parentNode.
connectedCallback() When an element is added to the DOM, the connectedCallback method is triggered. From that moment we can be sure that its available in the DOM and we're able to safely set attributes, fetch resources, run setup code or render templates.
There's a HTML5 API called MutationObserver and it has pretty good support
Here's an example:
// Element is the whatever subtree/element you need to watch over
var in_dom = document.body.contains(element);
var observer = new MutationObserver(function(mutations) {
if (document.body.contains(element)) {
if (!in_dom) {
console.log("element inserted");
}
in_dom = true;
} else if (in_dom) {
in_dom = false;
console.log("element removed");
}
});
observer.observe(document.body, {childList: true, subtree: 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