Skip to content

Instantly share code, notes, and snippets.

@elpuas
Last active June 28, 2021 19:38
Show Gist options
  • Save elpuas/9a8a227d82b2cb2f292e5bfcc3100053 to your computer and use it in GitHub Desktop.
Save elpuas/9a8a227d82b2cb2f292e5bfcc3100053 to your computer and use it in GitHub Desktop.
Waits for Element to exist on the DOM
/**
* Waits for an element satisfying selector to exist, then resolves promise with the element.
* Useful for resolving race conditions.
*
* @param selector
* @returns {Promise}
*/
function elementReady(selector) {
return new Promise((resolve, reject) => {
let el = document.querySelector(selector);
if (el) {resolve(el);}
new MutationObserver((mutationRecords, observer) => {
// Query for elements matching the specified selector
Array.from(document.querySelectorAll(selector)).forEach((element) => {
resolve(element);
//Once we have resolved we don't need the observer anymore.
observer.disconnect();
});
})
.observe(document.documentElement, {
childList: true,
subtree: true
});
});
}
elementReady('#_ghostery-title').then( (target) => {
target.focus()
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment