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
if you have async dom changes, this function checks (with time limit in seconds) for the DOM elements, it will not be heavy for the DOM and its Promise based :)
function getElement(selector, i = 5) {
return new Promise(async (resolve, reject) => {
if(i <= 0) return reject(`${selector} not found`);
const elements = document.querySelectorAll(selector);
if(elements.length) return resolve(elements);
return setTimeout(async () => await getElement(selector, i-1), 1000);
})
}
// Now call it with your selector
try {
element = await getElement('.woohoo');
} catch(e) { // catch the e }
//OR
getElement('.woohoo', 5)
.then(element => { // do somthing with the elements })
.catch(e => { // catch the error });