How to identify if an element was removed from the page in real time

4

How to identify with JavaScript, if the user removed a div from the page through the element inspector, ie if the id of the element no longer exists on the page, perform an action.

Simple example:

  • If% is removed, <div id="teste>
asked by anonymous 18.08.2018 / 16:45

1 answer

7

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.

    
18.08.2018 / 17:25