I have this scenario where I need to detect the removal of certain elements from the DOM. I can easily identify them when they are inserted to the DOM but I need also to detect when such elements are removed from the DOM.
Key facts:
I need to use DOM observer because the code managing the removal of this elements is outside of my control (and is totally external to my code).
For the sake of this discussion let's assume all elements that I care of can be identified by
class="my-class"
and that they can appear anywhere in the DOM structure.There can potentially numerous such elements (there is no known upper bound on the number of such elements).
I see two main approaches:
(1) Create a single MutationObserver and have it .observe(document.body, {subtree: true, childList: true})
. Each time my callback is called I will use querySelectorAll('.my-class')
on the removed elements to find if any of the elements that I care of are in the removed subtree.
(2) Create multiple MutationObservers: each time a new element that I care of (elem
) is inserted to the DOM my code will create a MutationObserver and will invoke .observe(elem, {})
. when my callback is called I can know that elem
was removed. Of course, I will also need to call the observer's .disconnect()
method at that point.
I wonder which of these two apporaches to take. In (1) there is just one instance whereas in (2) there are numerous instances.
On the other hand, in (1) the observation is deeper ({childList: true, subtree: true}
) and I need to run a selector query each time. In (2) the observation is shallow ({}
) and no selector query is needed.
I am looking for recommendation on which approach to take, this relates primarily to these questions: how expensive is each MutationObserver instance, how expensive is deep observation vs. a shllow one.