Question:
How to identify with JavaScript, if the user removed a div
from the page by the element inspector, ie if the element id
no longer exists on the page, perform an action.
Simple example:
- If the
<div id="teste>
is removed,document.getElementById("algum-id").innerHTML = ""
Answer:
If you want to understand when the DOM changes you should use MutationObserver . It allows defining a callback that executes whenever there is a change in a certain element and its descendants.
For the 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 the children, checking if any child is the <div id="teste">
.
The removal of children is given by the removedNodes
property of the change that was made, which is a list of the nodes that were removed in the DOM. Just check if the id of the one you are interested in there exists in 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 a certain point you no longer need to listen for events with this observer, you should turn off listening via:
observer.disconnect();
Not to weigh down on the page watching changes that you are no longer interested.