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