I\'m working on an Extension in Chrome, and I\'m wondering: what\'s the best way to find out when an element comes into existence? Using plain javascript, with an interval t
This is a simple solution for those who are used to promises and don't want to use any third party libs or timers.
I have been using it in my projects for a while
function waitForElm(selector) {
return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
const observer = new MutationObserver(mutations => {
if (document.querySelector(selector)) {
resolve(document.querySelector(selector));
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
To use it:
waitForElm('.some-class').then(elm => console.log(elm.textContent));
or with async/await
const elm = await waitForElm('.some-classs')