Skip to content

Instantly share code, notes, and snippets.

@littlepsylo
Forked from PaulKinlan/waitForElement.js
Created October 22, 2016 16:20
Show Gist options
  • Select an option

  • Save littlepsylo/9665541d8203054aa3eb30e1923f581f to your computer and use it in GitHub Desktop.

Select an option

Save littlepsylo/9665541d8203054aa3eb30e1923f581f to your computer and use it in GitHub Desktop.
waitForElement.js
function waitForElement(selector) {
return new Promise(function(resolve, reject) {
var element = document.querySelector(selector);
if(element) {
resolve(element);
return;
}
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var nodes = Array.from(mutation.addedNodes);
for(var node of nodes) {
if(node.matches && node.matches(selector)) {
observer.disconnect();
resolve(node);
return;
}
};
});
});
observer.observe(document.documentElement, { childList: true, subtree: true });
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment