Skip to content

Instantly share code, notes, and snippets.

@yaakov123
Created November 7, 2020 22:11
Show Gist options
  • Save yaakov123/5eb05791840a8774aaadeee0dc5bb63b to your computer and use it in GitHub Desktop.
Save yaakov123/5eb05791840a8774aaadeee0dc5bb63b to your computer and use it in GitHub Desktop.
// Select the node that will be observed for mutations
const bank = document.getElementById('bank');
// Options for the observer (which mutations to observe)
const config = { childList: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
// Loop through all mutations
mutationsList.forEach(mutation => {
// Loop through all added nodes
mutation.addedNodes.forEach(node => {
// If the node is a "robber"
if (node.id === 'robber') {
console.log('kicking robber out of bank')
node.parentNode.removeChild(node);
}
})
})
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(bank, config);
setTimeout(()=> {
// Add a "robber" to the bank
const robber = document.createElement('div');
robber.id = 'robber';
bank.appendChild(robber);
}, 1500);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment