there is one element on webpage I need to get, it usually takes some time to appear, so I googled out such solution which meets my requirement in How to wait until an element exists?
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
});
I have tested in my project, it will return the element if the target element is there at the beginning, but will report 'Uncaught (in promise) XX not found' error if the target element never appears, the worst case is nothing returns if the target element appears after trying times between 4 and 1, no exception, no element
what's wrong with the code? or how to fix it?
thanks.