Skip to content

Instantly share code, notes, and snippets.

@PaulKinlan
Last active July 19, 2022 22:32
Show Gist options
  • Save PaulKinlan/2d7cd4e78a63a97387137a0a9fb7ee6e to your computer and use it in GitHub Desktop.
Save PaulKinlan/2d7cd4e78a63a97387137a0a9fb7ee6e 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 });
});
}
@PaulKinlan
Copy link
Author

Note: @jaffathecake also pointed out that if we add in an element that is nested in another element via appendChild then it won't get picked up...

waitForElement("#test").then(el => {
// this won't fire.
alert(el);
});

var parent = document.createElement('div');
var child = document.createElement('div');
child.id = "test";
parent.appendChild(child);
document.documentElement.appendChild(parent);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment