What is the best way to verify a selector's existence in Puppeteer?

Determining Selector Presence

Use Puppeteer to detect a selector. For example, if ‘#elemStatus’ is absent, assign an empty string. Example code:

const pages = ['siteA', 'siteB'];
for (const link of pages) {
  await page.goto(link);
  let content = await page.$('#elemStatus') ? await page.evaluate(item => item.textContent, await page.$('#elemStatus')) : "";
}

A technique that has served me well involves using a short timeout with page.waitForSelector() to check for the element’s presence. I set the timeout to a few hundred milliseconds so that if the element is missing, the wait does not unnecessarily slow down the script. I then wrap the call in a try-catch block to gracefully handle the failure. This approach has the bonus of integrating error-handling directly in the flow, making it easier to decide on fallback actions without cluttering the main logic.

i lean on page.evaluate(()=>!!document.querySelector(‘#elemStatus’)); it directly returns a bool so i can skip the heavy waiting. this feels cleaner and avoids potential delays if the elem isnt there.

A method that I’ve found reliable is to use the page.$$ function, which returns an array of elements that match the selector. By checking the length of the returned array, you can quickly determine if the selector exists without relying on timeouts or additional error handling. I usually combine this with a straightforward conditional to proceed with further actions if the element is found. This method is not only direct but also makes the code cleaner since it avoids the need for wrapping calls inside try-catch blocks, keeping the logic simple and maintainable.