I have a node which is being added to the DOM is some unknown place. I have no idea what the parent will be, and the only assumption I can make is that it'll be in the subtree of document.body
.
Further, I can not assume the node will be added as itself; it might be hidden in the subtree of some other element when it enters the DOM.
I would like to have a callback occur when the element is removed from the DOM and when it is added.
I tried using Mutation Observer but it is the wrong tool for the job. Mutation Observers can not observe a specific element, but instead the children of one. Given that I don't know what the parent element will be, I can't observe the parent for the addition of this one specific child.
So far, the only solution I've been able to find is to use a mutation observer on THE ENTIRE DOM starting from document.body
with subtree, and then iterate through the entire subtree of every added node searching for the one node I'm looking for.
The next best solution I have is to check every node I'm trying to observe for being on the page anytime anything is added or removed. The big issue with this one is that it requires holding references to potentially deprecated HTMLELements, and would end up blocking the garbage collector.
Neither of these approaches is efficient.
Surely, there must be a better way? This can't be that hard of a problem, can it?
function onElementAdd(node, cb);
function onElementRemove(node, cb);