Skip to content

Instantly share code, notes, and snippets.

@vaaski
Last active January 20, 2021 10:25
Show Gist options
  • Select an option

  • Save vaaski/57cc3ca7446ddc81ea2bd919473456cf to your computer and use it in GitHub Desktop.

Select an option

Save vaaski/57cc3ca7446ddc81ea2bd919473456cf to your computer and use it in GitHub Desktop.
get an element with querySelector or wait for it using MutationObserver
/**
* get an element with querySelector or wait for it using MutationObserver
* @param {string} selector a css selector
* @param {HTMLElement} parent the parent in which to search for
* @returns {Promise<HTMLElement>}
*/
const getElement = (selector, parent = document) => {
return new Promise(res => {
let query = parent.querySelector(selector)
if (query) return res(query)
let timeout = 0
const observer = new MutationObserver((list, obs) => {
for (const mutation of list) {
if (mutation.type === "childList") {
query = parent.querySelector(selector)
if (query) {
obs.disconnect()
clearTimeout(timeout)
return res(query)
}
}
}
})
observer.observe(parent, { childList: true, subtree: true })
timeout = setTimeout(() => {
observer.disconnect()
console.log(`observer for ${selector} timed out`)
return res(document.createElement("div"))
}, 5e3)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment