Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Created March 24, 2023 19:44
Show Gist options
  • Save crazy4groovy/e4a8542281c149102fe6bdac9678777e to your computer and use it in GitHub Desktop.
Save crazy4groovy/e4a8542281c149102fe6bdac9678777e to your computer and use it in GitHub Desktop.
Detect changes to an element/parent or its children with MutationObserver (JavaScript)
const parentEl = document.querySelector('.my-parent')
const callback = (mutationList, observer) => {
for (const mutation of mutationList) {
if (mutation.type === "childList") {
console.log("A child node has been added or removed.", mutation);
}
if (mutation.type === "attributes") {
console.log(`The ${mutation.attributeName} attribute was modified.`, mutation.target[mutation.attributeName]);
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Observe some elements
const config = { attributes: true, childList: true, subtree: true };
observer.observe(parentEl, config)
// ex: Disconnect whenever you want
setTimeout(() => observer.disconnect(), 5000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment