How to verify if DOM elements exist using Puppeteer

I’m trying to figure out how to validate whether specific elements are present on a webpage using Puppeteer in Node.js. My current approach doesn’t seem to work properly.

Here’s what I’ve attempted so far:

let elementExists = false;

if(await page.$('button[data-testid="user-123456789-btn"]')) {
    elementExists = true;
}

if(elementExists === true) {
    console.log("Element was found");
} else {
    console.log("Element not found");
}

What I’m trying to accomplish is this: I have a webpage that contains form elements with IDs numbered from 1 to 20. These numbers might not be sequential and could start from any number. For instance, the page might have elements with IDs 3, 4, 5, 6, 7 or maybe 8, 9, 10, 11, 12, 13.

I want to loop through each possible ID number and check if an element with that ID actually exists on the page. When I find one that exists, I need to set my variable to true and proceed with my logic.

Basically, I need a reliable way to detect if a specific selector matches any element in the DOM or not.

Had this exact problem last month. page.waitForSelector() with a timeout works way better than just checking if an element exists right now. It’ll actually wait for the element to show up, which is super helpful when the page’s still loading.

try {
    await page.waitForSelector('button[data-testid="user-123456789-btn"]', { timeout: 1000 });
    console.log("Element found");
} catch (error) {
    console.log("Element not found");
}

This saved me from those annoying false negatives when elements were slow to render. The timeout stops it from hanging forever but gives elements time to load. Just adjust the timeout based on how fast your page loads.

hey, try using page.$$eval() instead. it returns an array, so u can check the length: const count = await page.$$eval('button[data-testid="user-123456789-btn"]', els => els.length); then just check if count > 0. way easier!

Your page.$() approach is correct, but you can simplify it. The method returns null when no element exists, so just check the result directly:

const element = await page.$('button[data-testid="user-123456789-btn"]');
if (element) {
    console.log("Element was found");
} else {
    console.log("Element not found");
}

For numbered IDs, loop through the range and break when you find a match:

let foundElement = null;
for (let i = 1; i <= 20; i++) {
    const selector = `#element-${i}`;
    foundElement = await page.$(selector);
    if (foundElement) {
        console.log(`Found element with ID: ${i}`);
        break;
    }
}

This works reliably and keeps things simple. page.$() is built for checking if elements exist.