Event for when an element is added/removed from the DOM, without knowing the parent element

I have a function similar to this:

function makeSomeElement() {
    const out = document.createElement("div");
    // do some things with out

    // pseudo code for what I am looking for
    out.onadded = () => { ... }
    out.onremoved = () => { ... }

    return out;
}

As you can see the function knows nothing about the parent element.

As far as I know MutationObserver only observer child elements, attributes and text.

Basically I want to execute a function every time out is added or removed from the DOM. I feel like I have missed something painfully obvious.

The only solution I see, is making a Web Component class with the functions connectedCallback and disconnectedCallback. That seems a lot more complicated that it should be.

66 thoughts on “Event for when an element is added/removed from the DOM, without knowing the parent element”

Leave a Comment