Skip to content

Instantly share code, notes, and snippets.

@MarcelloTheArcane
Created October 26, 2021 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarcelloTheArcane/4e1d9458929d48fa1b962b88e400ccdc to your computer and use it in GitHub Desktop.
Save MarcelloTheArcane/4e1d9458929d48fa1b962b88e400ccdc to your computer and use it in GitHub Desktop.
Wait for an element to be inserted to the DOM. It tries a query selector on all mutation events.
// This assumes that the selector will eventually appear - it'll hang indefinitely otherwise.
// You may need a slight delay after this returns, for the element to have its event handlers attached.
async function waitForElementToExist (selector) {
return new Promise(resolve => {
const observer = new MutationObserver(() => {
const element = document.querySelector(selector)
if (element) {
observer.disconnect()
return resolve(element)
}
})
observer.observe(document, {
childList: true,
subtree: true,
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment