How to identify if an item has been removed from the page in real time

Asked

Viewed 115 times

4

How to identify with Javascript, if the user has removed a div of the page by the, or element inspector, that is to say, if the id element no longer exists on page, perform an action.

Simple example:

  • If the <div id="teste>, document.getElementById("algum-id").innerHTML = ""
  • Vishe, stopping to think now, you want to detect in real time if the element has been excluded, right?

  • Exactly in real time, onload is good simple and is not what I seek..

  • 2

    If the goal is to realize at the moment a certain element has been removed then the path is to use Mutationobserver. By the question to me it was not very clear

  • @Isac This then solves his problem yes, outside that it is already explained on the page of the function itself, reply with the link that is correct.

1 answer

7


If you want to understand when the FOD is changed you should use Mutationobserver. This allows you to define a callback which it implements whenever there is a change in a given element and its descendants.

For example the ideal is to define the observation in the parent element of the one you want to remove, and listen for the removal of children, checking if any child is the <div id="teste">.

The removal of children is given by the property removedNodes of the change that has been 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 there exists on that list.

Example (adapted from 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 some point you no longer need to listen to events with this observer, you should turn off the listening by:

observer.disconnect();

Not to weigh in the page observing changes that are no longer interested.

  • Our...........

Browser other questions tagged

You are not signed in. Login or sign up in order to post.