Skip to content

Instantly share code, notes, and snippets.

@dnyall
Created July 30, 2023 12:08
Show Gist options
  • Save dnyall/a016ab0c8232aa1f68207a653cab14c4 to your computer and use it in GitHub Desktop.
Save dnyall/a016ab0c8232aa1f68207a653cab14c4 to your computer and use it in GitHub Desktop.
watchForElement function - if specefic element add or remove from dom
watchForElement(className , cb) {
const observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
const addedNodes = Array.from(mutation.addedNodes);
const elementExists = addedNodes.some(node => node.classList && node.classList.contains(`${className}`));
if (elementExists) {
// Element with the specific class has been added to the DOM
console.log('Element added!');
cb();
}
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment