Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!