Created
March 24, 2023 19:44
-
-
Save crazy4groovy/e4a8542281c149102fe6bdac9678777e to your computer and use it in GitHub Desktop.
Detect changes to an element/parent or its children with MutationObserver (JavaScript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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