prevent a node from removing from the DOM

Viewed 665

I want to prevent an element from being removed by using something like preventDefault(). Ex.

myNode.on("remove", (e) => {
       e.preventDefault();
    });

I can detect the removal by using MutationObserver but I can't prevent the element from removing. Appreciate your help.

1 Answers

You can't. There's no event fired (other than the deprecated mutation events, and they weren't cancellable), mutation observers can't prevent it from happening, etc.

You can detect it happened and put it back, but you can't prevent that specific one from being removed.

Here's a minimal example of doing that; in this case, the code assumes it should be at the top of its parent, but of course that's not true all the time. If you have to insert it somewhere special, you'll need to know where it goes before it's removed.

const observer = new MutationObserver(records => {
    for (const {target, removedNodes} of records) {
        const element = Array.prototype.find.call(removedNodes, ({id}) => id === "the-element");
        if (element) {
            console.log("Re-inserted at top of parent");
            target.insertBefore(element, target.firstChild);
        }
    }
});
observer.observe(document.body, {
    subtree: true,
    childList: true
});
document.getElementById("the-btn").addEventListener("click", () => {
    document.getElementById("the-element").remove();
});
<div>
  <div id="the-element">this is the element</div>
  <input id="the-btn" type="button" value="Remove It">
</div>

Related