Introduced in Selenium 4, relative locators (also known as friendly locators) allow you to locate an element based on its visual relationship to another known element on the page. They are particularly useful for elements that lack unique identifiers. The available relative locators are:
above()
: Locates an element visually above another.below()
: Locates an element visually below another.toLeftOf()
: Locates an element to the left of another.toRightOf()
: Locates an element to the right of another.near()
: Locates an element within a certain proximity (default 50 pixels) of another.
Example: driver.findElement(with(By.tagName("input")).below(By.id("username")));