Reputation: 3042
I want to observe and element that sometimes gets deleted and then recreated. My problem is that the observer gets destroyed with the element and doesn't get recreated with the element, and I have no way to detect when that happens in order to re-create the observer.
MDN says that "Note: According to specification a MutationObserver is deleted by the garbage collector if the target element is deleted."
Is there anyway to detect that deletion? I'm observing an element, I want to know when that element was deleted. I can detect if its sub-nodes have been deleted, but I have no way to detect if it itself has been removed.
I registered to all mutations but the callback doesn't get called when the element is deleted.
I tried setInterval to check every second if the element disappears but this doesn't work well when the element gets removed and then re-created quickly.
Upvotes: 5
Views: 4553
Reputation: 20125
A MutationObserver doesn't fire when the element on which it is set is removed. The specification only allows to listen for changes on attributes, character data and child nodes.
So the solution to this is to set the MutationObserver on the parent (or ancestor) element that is not deleted. In the callback you then have to loop through the MutationRecords to check whether their removedNodes
property contains the element you are looking for.
The code for that will look something like this:
let mutationObserver = new MutationObserver((mutationList, observer) => {
for (let mutationRecord of mutationList) {
if (mutationRecord.removedNodes) {
for (let removedNode of mutationRecord.removedNodes) {
if (removedNode.id === 'myElement') {
...
return;
}
}
}
}
});
The return
statement is in there to stop looping through the rest of the elements once you handled the deletion of the searched element.
Upvotes: 8