Selecting Elements by Label Text in Playwright

You can target the label to perform an action on the associated control. Targeted input actions in Playwright automatically distinguish between labels and controls like input box, dropdown, upload, or any other control.

For example, consider the create new account page of the programsbuzz website. We can fill in a Username, upload a Profile Picture, or select an Interest dropdown value by targeting its label as a selector and performing actions using methods like fill, setInputFiles, or selectOption, respectively.

Selecting Elements by Label Text in Playwright

Table of Content

  1. Focus on input using the label
  2. Fill in input using the label
  3. Get the input value using the label
  4. Select the input value using the label
  5. Upload file using the label
  6. Select the dropdown value using the label
  7. Video Tutorial

1. Focus on input using the label

The click method will click the label and automatically focus the input field associated with the label.

await page.locator('text=Username').click()

2. Fill in input using the label

The fill method will fill the input field associated with the label.

await page.locator('text=Username').fill('hello')

3. Get the input value using the label

The inputValue method will return the value of the input field.

await page.locator('text=Username').fill('hello')
console.log(await page.locator('text=Username').inputValue())

4. Select the input value using the label

The selectText will select text in the input field.

await page.locator('text=Username').fill('hello')
await page.locator('text=Username').selectText()

5. Upload file using the label

The setInputFiles will set files for the input field with type=file.

await page.locator('text=Profile Picture').setInputFiles('tests/myfilename.js')

6. Select the dropdown value using the label

The selectOption will select an option from the select box.

await page.locator('text=Interest').selectOption('Data Science')

Note: not all methods will target the associated control. For example, textContent will return the text content of the label, not the input field.

Tue, 09/27/2022 - 21:42

Authored by

Tarun Goswami, works as a Technical Lead at the well-known IT services company. With Over 11+ years of experience in Quality Assurance, he writes engaging and informative blogs in his spare time.

Video Tutorial: Selecting Elements by Label Text in Playwright

Tags