If you want to see when the DOM changes, you should use MutationObserver . This allows you to define a callback that executes whenever there is a change in a particular element and its descendants.
For example, it is best to set the observation on the parent element of the parent that you want to remove, and listen for child removal by checking if any child is <div id="teste">
.
Removing children is given by the removedNodes
property of the change that was made, which is a list of nodes that have been removed in the DOM. Just check if the id of the one you're interested in exists in this list.
Example (adapted from the documentation):
document.getElementById("remover").addEventListener("click", function() {
document.getElementById("conteudo").innerHTML = "";
});
//no pai do que pretende escutar as alterações
const targetNode = document.getElementById('conteudo');
const config = { childList: true, subtree: true};
const observer = new MutationObserver(function(mutationsList) {
for (let mutation of mutationsList) { //para cada uma das alterações no DOM
if (mutation.type == 'childList') { //se afeta os filhos
const removedIds = [...mutation.removedNodes].map(x => x.id); //apanhar os id's
if (removedIds.includes("teste")){ //se o id existe é porque foi removido
console.log("teste removido");
}
}
}
});
observer.observe(targetNode, config);
<div id="conteudo">
<div id="teste">Div teste aqui</div>
</div>
<button id="remover">Remover</div>
If at any point in time you no longer need to listen to events with this viewer, you should turn off the listener by:
observer.disconnect();
To not weigh the page by looking at changes that are no longer interested.