Skip to content

Instantly share code, notes, and snippets.

@cdcharlebois
Created April 15, 2022 16:22
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 cdcharlebois/1fd0dfff6faff83f8afde22d730f60e4 to your computer and use it in GitHub Desktop.
Save cdcharlebois/1fd0dfff6faff83f8afde22d730f60e4 to your computer and use it in GitHub Desktop.
Use this to wait for an element to be rendered before continuing
// from https://stackoverflow.com/a/61511955/1513051
function waitForElement(selector) {
return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
const observer = new MutationObserver(mutations => {
if (document.querySelector(selector)) {
resolve(document.querySelector(selector));
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
/*
Ex.
const el = await waitForElement('.some-classname')
// do something with el
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment