Home > Software engineering >  is it possible to observe element existence and removal permanently using JS MutationObserver?
is it possible to observe element existence and removal permanently using JS MutationObserver?

Time:01-14

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')
    }
});

CodePudding user response:

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>

CodePudding user response:

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>

  •  Tags:  
  • Related