Being new to the world of MutationObserver, I am trying to grasp how to detect the existence or permanent removal of an element. I stumbled upon an example that seemed promising, but it only works for detecting the element's presence once - not its removal or subsequent re-appearance.
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')
}
});