How to target HTML element by text content using puppeteer

I’m working on a puppeteer automation script and need help selecting a button element based on its text content. My HTML has a button like this:

<button>Settings</button>

I tried using a value selector in my code:

await page.type('button[value="Settings"]');
await page.click('button[value="Settings"]');

But this approach doesn’t work because the button doesn’t actually have a value attribute. I get an error saying no element was found with that selector. What’s the correct way to select and interact with buttons based on their displayed text content in puppeteer?

You can also use page.evaluate() to find buttons by their text:

const button = await page.evaluate(() => {
  return [...document.querySelectorAll('button')].find(btn => btn.textContent.trim() === 'Settings');
});

This gives you more flexibility for text matching!

Try using page.waitForSelector with the ::-p-text() pseudo-selector instead. It’s built specifically for text-based selection in Puppeteer and I’ve found it way more reliable than XPath:

await page.waitForSelector('button::-p-text(Settings)');
await page.click('button::-p-text(Settings)');

This waits for a button with the exact text “Settings” then clicks it. Works great for dynamic content that loads after the page renders. It plays nicer with Puppeteer’s waiting mechanisms and performs better than XPath for text selections.

When you need to select a button element by its visible text using Puppeteer, XPath is your best option. Your previous approach with the value attribute won’t work since the button lacks that attribute. Instead, you can use the following XPath syntax to target the button by its text:

const [button] = await page.$x("//button[contains(text(), 'Settings')]");
if (button) {
    await button.click();
}

This code snippet searches for any button element that contains the text ‘Settings’. It’s robust against variations like extra whitespace or inner elements, so ensure you check if the button exists to avoid errors.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.