Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda