1

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.

tiplip
  • 329
  • 5
  • 17
  • 1
    [That answer](https://stackoverflow.com/a/61640061/1048572) has the most horrible code from all the answers on that page. Why not choose [this solution](https://stackoverflow.com/a/61511955/1048572) instead? – Bergi Dec 05 '20 at 15:21
  • 1
    @Bergi thanks, "Why not choose [this solution](https://stackoverflow.com/questions/5525071/how-to-wait-until-an-element-exists/61511955#61511955) instead?" It does not handle the failed case, for instance, I will only wait 5 seconds, if the target does not appear, I will print "error", for [that answer](https://stackoverflow.com/questions/5525071/how-to-wait-until-an-element-exists/61640061#61640061), I just remove 'async', seems not working, how to make it work? – tiplip Dec 06 '20 at 00:48
  • Just add a `const timer = setTimeout(() => { observer.disconnect(); reject(new Error("Element did not appear in time")); }, 5000);` to the promise executor and `clearTimeout(timer);` next to the `resolve` call. – Bergi Dec 06 '20 at 11:29
  • @Bergi cool, helpful – tiplip Dec 06 '20 at 23:50

0 Answers0