Relative Locators

Locating by Position

Selenium 4 can find an element by where it is on screen relative to another element. Useful when a field has no good attributes but its label does.

<label for="f1">Email</label>     <input id="f1">
<label for="f2">Password</label>  <input id="f2">
<button>Cancel</button>  <button>Login</button>

The Methods

import static org.openqa.selenium.support.locators.RelativeLocator.with;

WebElement emailLabel = driver.findElement(By.xpath("//label[text()='Email']"));
WebElement password = driver.findElement(By.xpath("//label[text()='Password']"));

WebElement emailBox    = driver.findElement(with(By.tagName("input")).toRightOf(emailLabel));
WebElement passwordBox = driver.findElement(with(By.tagName("input")).below(emailBox));
WebElement login       = driver.findElement(with(By.tagName("button")).toRightOf(By.xpath("//button[text()='Cancel']")));
WebElement nearLabel   = driver.findElement(with(By.tagName("input")).near(password));   // within 50 px

emailBox.sendKeys("[email protected]");
MethodFinds an element that is
above(el)higher on the page
below(el)lower on the page
toLeftOf(el) / toRightOf(el)left / right of it
near(el)within 50 pixels

Limits

  • Positions come from the rendered layout, so results change with window size and responsive layouts. Set a fixed window size.
  • Chain conditions to be precise: with(By.tagName("input")).below(emailBox).above(loginBtn).
  • Prefer id, name, CSS or XPath when they exist. Relative locators are a helper, not the first choice.