Skip to content

Instantly share code, notes, and snippets.

@klaaz0r
Last active October 12, 2022 11:34
Show Gist options
  • Save klaaz0r/7f5880f0b11d00048e0b21273716d8d6 to your computer and use it in GitHub Desktop.
Save klaaz0r/7f5880f0b11d00048e0b21273716d8d6 to your computer and use it in GitHub Desktop.
Wait for a DOM element to appear with a MutationObserver
const waitForElement = selector => new Promise((resolve, reject) => {
const element = document.querySelector(selector);
if (element) {
return resolve(element);
}
const timeout = setTimeout(() => reject(new Error('element not found')), 15000);
const walkDOM = (node, fn) => {
if (node.matches && node.matches(selector)) {
return fn(node);
}
node = node.firstChild;
while (node) {
walkDOM(node, fn);
node = node.nextSibling;
}
};
try {
const observer = new MutationObserver((mutations => {
mutations.forEach(mutation => {
const nodes = Array.from(mutation.addedNodes);
return nodes.forEach(node => walkDOM(node, match => {
observer.disconnect();
clearTimeout(timeout);
return resolve(match);
}));
});
}));
observer.observe(document.documentElement, { childList: true, subtree: true });
} catch (err) {
return reject(err);
}
});
@PhenX
Copy link

PhenX commented Oct 12, 2022

The observer should also be disconnected on timeout, no ?

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