Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM event when element is removed

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.

like image 497
Marius Avatar asked Oct 16 '18 11:10

Marius


People also ask

Does removing element from DOM remove event listeners?

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.

How can you tell if a element is removed from DOM?

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.

How do you remove an element from a DOM?

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.

Which method is triggered when an element is added to the DOM?

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.


1 Answers

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});
like image 88
Tareq El-Masri Avatar answered Sep 25 '22 07:09

Tareq El-Masri