Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I select an element by data-testid using #?

Just like the id can be selected using

await page.locator("#YourId").click()

is there a shorthand for data-testid in playwright-typescript ?

I tried

await page.locator("#YourData-testid").click()

I was expecting the element with the data-testid to be clicked but it is not located for click action.

like image 667
Pallavi Avatar asked Oct 20 '25 14:10

Pallavi


1 Answers

The # shorthand symbol for id is actually specific to/provided by CSS selectors, which is what’s being used by .locator(). Since data-testid is nothing special to css selectors, since it’s not meant for styling, the only way with css selectors is with the attribute notation:

.locator('[data-testid="value"]')

That being said, Playwright does provide the .getByTestId() convenience method for selecting by that attribute:

.getByTestId('value')
like image 188
David R Avatar answered Oct 22 '25 02:10

David R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!