Skip to content

Instantly share code, notes, and snippets.

@jackrobertscott
Created December 17, 2019 07:30
Show Gist options
  • Save jackrobertscott/f0d81f7cefb95050c07ba93183081f99 to your computer and use it in GitHub Desktop.
Save jackrobertscott/f0d81f7cefb95050c07ba93183081f99 to your computer and use it in GitHub Desktop.
Simple mutation observer on attributes.
/**
* Mutation observer is not a big library. Rather it's a simple way to observe:
* 1. New attributes on nodes.
* 2. Added / removed node to document.
* 3. Changes to "contenteditable" text elements.
*/
const observer = new MutationObserver((mutationsList, observer) => {
for (let mutation of mutationsList) {
if (mutation.type === 'attributes') {
console.log(mutation.attributeName)
}
}
})
observer.observe(document, {
subtree: true,
attributes: true,
attributeFilter: ['data-authpack']
})
setTimeout(() => {
const node = document.createElement('div')
const parent = document.querySelectorAll('[data-authpack]')[0]
if (parent) parent.appendChild(node)
node.dataset.authpack = 'hello'
setTimeout(() => observer.disconnect())
}, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment