Search code examples
playwright

Playwright selecting element with text= or hastext with exact match


I'm using playwright nodejs. I've written myself a little dynamic selector function to select the page number button on a dataTable.

pageNumberButton(page, table_id, page_number) {
   page.locator(`[aria-controls=${table_id}]`, {hasText: page_number});
}

I've also tried:

pageNumberButton(page, table_id, page_number) {
   page.locator(`[aria-controls=${table_id}] text=${page_number}`);
}

However, I can't seem to make it do an exact match.

Suppose my dataTable has 13 pages:

dataTable button controls showing Previous, 1, 2, 3, 4, 5, ..., 13, Next button

and I wish to click on page 1. so I issue the following command: await pageNumberButton(page, "resultsTable", "1").click();

But I get a strict-mode error, since there are two results: 1 and 13.

What would be the best, or good, way to create this little selector dynamically so that I can do an exact match for the button?


Solution

  • text body can be escaped with single or double quotes to search for a text node with exact content

        pageNumberButton(page, table_id, page_number) {
           page.locator(`[aria-controls=${table_id}]`)
               .filter({ has: page.locator(`text="${page_number}"`) });
        }