Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
is it possible to observe element existence and removal permanently using JS MutationObserver?

I'm completely new with MutationObserver. I need to detect if an element exists or is removed permanently. I found that example which really awesome. but it works just for element existence and just once for the first time! it doesn't feel element removal and never feels element existence after the first time.

HTML

<button onclick="appendS()">add message</button>
<button onclick="remove()">remove message</button>
<div id='imobserved'></div>

CSS

button{padding:30px; margin: 10px;}
#imobserved{border: 1px solid black; padding: 10px;}

JS

function appendS(){
  let s = document.createElement('span');
  s.id = "message";
  s.innerText = "some message !"
  document.querySelector('#imobserved').appendChild(s);
}

function remove(){
  document.querySelector('#imobserved').innerHTML = "";
}

function waitForAddedNode(params) {
    new MutationObserver(function(mutations) {
        var el = document.getElementById(params.id);
        if (el) {
            this.disconnect();
            params.done(el);
        }
    }).observe(params.parent || document, {
        subtree: !!params.recursive || !params.parent,
        childList: true,
    });
}

// Usage:

waitForAddedNode({
    id: 'message',
    parent: document.querySelector('#imobserved'),
    recursive: false,
    done: function(el) {
        alert('i see you')
    }
});
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Here is how you can achieve it. I've changed your code a little bit
First of all, never create multiple DOM elements with the same ID, this is a bad idea. In the MutationObserver callback, you have plenty of information, including about which nodes have been added and which have been removed.


Feel free to run the snippet below, and see how it behaves.

function appendS() {
  let s = document.createElement("span");
  s.innerText = "some message !";
  document.querySelector("#imobserved").appendChild(s);
}

function remove() {
  document.querySelector("#imobserved").innerHTML = "";
}

function waitForAddedNode(params) {
  new MutationObserver(function (mutationsList) {
    for (const mutation of mutationsList) {
      if (mutation.addedNodes.length) {
        params.onAdd(mutation.addedNodes);
      }

      if (mutation.removedNodes.length) {
        params.onDelete(mutation.removedNodes);
      }
    }
  }).observe(params.parent, {
    childList: true,
    subtree: true
  });
}

waitForAddedNode({
  parent: document.querySelector("#imobserved"),
  recursive: false,
  onAdd: function (elements) {
    alert("i see you added new element");
    console.log(elements);
  },
  onDelete: function (elements) {
    alert("i see you removed " + elements.length + " elements");
    console.log(elements);
  }
});

const addBtn = document.querySelector("#add");
const removeBtmn = document.querySelector("#remove");

addBtn.addEventListener("click", appendS);
removeBtmn.addEventListener("click", remove);
button {
  padding: 30px;
  margin: 10px;
}
#imobserved {
  border: 1px solid black;
  padding: 10px;
}
<body>
    <button id="add">add message</button>
    <button id="remove">remove message</button>
    <div id="imobserved"></div>
</body>

about 4 years ago · Juan Pablo Isaza Relatório

0

const observedEl = document.querySelector('#imobserved')

function append() {
  const s = document.createElement('span');
  s.id = "message";
  s.innerText = "some message!";

  observedEl.appendChild(s);
}

function remove() {
  if (observedEl.lastChild) {
    observedEl.lastChild.remove();
  }
}

const observer = new MutationObserver(function(e) {
  const addition = e[0].addedNodes.length;
  const message = addition ? 'Element added' : 'Element deleted'
  alert(message);
});

observer.observe(observedEl, {
  subtree: true,
  childList: true
});
button {
  padding: 30px;
  margin: 10px;
}

#imobserved {
  border: 1px solid black;
  padding: 10px;
}
<button onclick="append()">add message</button>
<button onclick="remove()">remove message</button>
<div id='imobserved'></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda