How to select an input according to a parent sibling label

Viewed 500

The input element that I have does not have anything to identify it because is my page is built through a react framework. So I want to select the appropriate input by its label above it. My HTML looks like the following:

<div>
  <label>Project</label>
</div>
<div>
  <div>
        <input>
  </div>
</div>
<div>
  <label>Type</label>
</div>
<div>
  <div>
        <input>
  </div>
</div>
2 Answers

If you try to perform an action on a label which has associated input element Playwright will automatically retarget the action to the input.

If the DOM structure is always the same you can try something like this

page.locator('div:has( > :text-matches("Project")) + div input')

Otherwise layout selector is your best bet.

You could try with layout selectors:

const div = page.locator('input:right-of(:text("Project"))');
Related