In this blog, we will explore Playwright Java's relative locators, that can be used to locate elements positioned above/below/near/right/left of a given element.
Topics that we will cover:
- Usage of Relative Locator ‘below’
- Usage of Relative Locator ‘above’
- Usage of Relative Locator ‘near’
- Usage of Relative Locator ‘right-of’
- Usage of Relative Locator ‘left-of’
- Source code
Usage of Relative Locator ‘below’
Go to https://opensource-demo.orangehrmlive.com/
As can be seen below, the input ‘Username’ field is “below”
‘Username’ text label

Let us try to enter text “rahulshettyacademy” using “below” locator.
Line#26 will help us to achieve that. The ‘Username’ input field is
represented by ‘input’ tag and hence we have used ‘input’ tag just before “below”

Execute the code.
The text “rahulshettyacademy” gets typed in the ‘Username’ input field

Usage of Relative Locator ‘above’
Let us navigate to https://sso.teachable.com/secure/9521/identity/login/password

As seen above, there is an ‘Email’ field above ‘Password’ field.
We can apply the same logic in this scenario as well

Execute the code.
Notice below that Playwright types the text in the ‘Email’ input text field

This is the way in which we can make use of the "above" method of the relative locator.
Usage of Relative Locator ‘near’
Go to https://rahulshettyacademy.com/AutomationPractice/
As can be seen below, the dropdown field is “near” ‘Dropdown’ text

Let us try to select “Options1” using “near” locator. Line#27 will help us to achieve that. The dropdown is represented by ‘select’ tag and hence we have used ‘select’ tag just before “near”

Execute the code.
“Option1” gets selected

Usage of Relative Locator ‘right-of’
Go to https://rahulshettyacademy.com/seleniumPractise/#/offers
As can be seen below, the dropdown field is “right-of” ‘Page size’ text

Let us try to select “20” using “right-of” locator. Line#27 will help us to achieve that. The dropdown is represented by ‘select’ tag and hence we have used ‘select’ tag just before “right-of”

Usage of Relative Locator ‘left-of’
Launch https://rahulshettyacademy.com/
As can be seen below, the “REGISTER” link is “left-of” LOGIN link

Let us try to click “REGISTER” link using “left-of” locator. Line#27 will help us to achieve that. The link is represented by ‘a’ tag and hence we have used ‘a’ tag just before “left-of”

Execute the code.
The registration page opens up

Source code (near)
Thanks.