Skip to content

Instantly share code, notes, and snippets.

@gsmartagence
Last active December 29, 2019 16:58
Show Gist options
  • Select an option

  • Save gsmartagence/9ef227ab5c737306863f93c3e2de2bac to your computer and use it in GitHub Desktop.

Select an option

Save gsmartagence/9ef227ab5c737306863f93c3e2de2bac to your computer and use it in GitHub Desktop.
{
"name": "waitForElement.js",
"version": "0.1.0"
}
/**
* wait for element to be created
* https://paul.kinlan.me/waiting-for-an-element-to-be-created/
* ESM version
*/
export const waitForElement = function (selector) {
return new Promise(function (resolve, reject) {
const element = document.querySelector(selector)
if (element) {
resolve(element)
return
}
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
const nodes = Array.from(mutation.addedNodes)
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i]
if (node.matches && node.matches(selector)) {
observer.disconnect()
resolve(node);
return;
}
}
})
})
observer.observe(document.documentElement, {
childList: true,
subtree: true
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment