Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select an element by Id?

Tags:

playwright

I wonder how I can access an element by ID. I want to submit a form.

  • await page.click("id= 'next'"); --> not possible
  • await page.getByRole('button', { id: 'next' }).click(); --> does not compile
  • await page.getByRole('button', { name: 'Sign in' }).click(); --> work but is language dependent

Selecting elements by their ID seems the most robust to me. Am I missing something?

like image 283
Johannes Schacht Avatar asked Aug 31 '25 10:08

Johannes Schacht


2 Answers

You can do something like this:

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

or just

await page.click("#YourId");

Playwright recommends some predefined locators so you could also check if some off those fit your use case.

like image 53
Basti Avatar answered Sep 06 '25 14:09

Basti


What you are missing in the first example are the square brackets, instead of:

await page.click("id= 'next'");

you should do this:

await page.click("[id='next']");

alternatively, you can use the shorthand version like mentioned in the other answer

like image 26
Artur Avatar answered Sep 06 '25 12:09

Artur