Last active
October 12, 2022 11:34
-
-
Save klaaz0r/7f5880f0b11d00048e0b21273716d8d6 to your computer and use it in GitHub Desktop.
Wait for a DOM element to appear with a MutationObserver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The observer should also be disconnected on timeout, no ?