Created
April 15, 2022 16:22
-
-
Save cdcharlebois/1fd0dfff6faff83f8afde22d730f60e4 to your computer and use it in GitHub Desktop.
Use this to wait for an element to be rendered before continuing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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