Skip to content

Instantly share code, notes, and snippets.

@luan0ap
Created March 14, 2023 20:53
Show Gist options
  • Save luan0ap/40a51ff663686b6fbea39ce74744afca to your computer and use it in GitHub Desktop.
Save luan0ap/40a51ff663686b6fbea39ce74744afca to your computer and use it in GitHub Desktop.
Wait for an element be on DOM
function waitForElm <T extends Element> (selector: string): Promise<T | null> {
return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector) as T | null);
}
const observer = new MutationObserver(() => {
if (document.querySelector(selector)) {
resolve(document.querySelector(selector) as T | null);
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment