Detect that given element has been removed from the DOM without sacrificing performance
07:51 17 May 2018

I've got these:

const element = this.getElementById("victim")

function releaseKraken(targetElement) {}

I want the function to be called when element is removed from DOM.

I can imagine something like this:

element.onRemove(() => releaseKraken(element))

I understand that I need MutationObserver, but all the documentation I found focuses on watching given element's children, whereas I need to watch the element itself.

UPD: the question How to detect element being added/removed from dom element? focuses on watching children of a given parent. I don't want to watch children or parent. I want to be notified when given element is removed from the DOM. Not it's children. And I don't want to set up a watcher on given element's parent (unless that's the only option) because it'll be a performance impact.

UPD2: if I set up a MutationObserver on document, this will result in the callback being triggered thousands or even millions of times per session, and each time the callback will have to filter a huge list of removed elements to see if it contains the one in question. That's just crazy.

I need something simple like I showed above. I want the callback to be triggered exactly once: when the given element is removed.

javascript html dom mutation-observers