Using Selenium 4 Relative Locators in Java: A Practical Guide
Learn how Selenium 4’s relative locators let you find elements by spatial relationships, see a worked Java example, and avoid common pitfalls.
21 Jan 2026, 15:03 UTC

What Are Relative Locators?
Relative locators let you locate an element by describing its position relative to another element in the page. The most common spatial relationships are above, below, toLeftOf, toRightOf, and near. They are part of Selenium 4’s org.openqa.selenium.support.locators.RelativeLocator API and are especially handy when the target element lacks a unique ID or class.
Setting Up Selenium 4 for Relative Locators
- Make sure you are using Selenium 4.x. In Maven, add the dependency:
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.15.0</version> </dependency> - Download the matching WebDriver binary (e.g., geckodriver for Firefox, chromedriver for Chrome) and place it in a directory that is on your system
PATHor reference it explicitly in your code. - Use
WebDriverWaitto guarantee that the reference element is present before applying a relative locator.
A Concrete Java Example
Below is a minimal test that opens a page, finds a reference element, and then uses a relative locator to click a button that appears below that reference.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.locators.RelativeLocator;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class RelativeLocatorDemo {
public static void main(String[] args) {
// 1. Set up WebDriver (Chrome in this example)
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
// 2. Navigate to a demo page
driver.get("https://example.com/demo-page-with-buttons");
// 3. Locate the reference element – e.g., a heading
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement heading = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.cssSelector("h2#login-header"))
);
// 4. Use a relative locator to find the button below the heading
WebElement submitBtn = driver.findElement(
RelativeLocator.with(By.tagName("button")).below(heading)
);
// 5. Verify and interact
System.out.println("Found button text: " + submitBtn.getText());
submitBtn.click();
// 6. Clean up
driver.quit();
}
}
What Happens Under the Hood?
The RelativeLocator.with() call creates a selector that instructs the browser to query the DOM for all button elements. The driver then filters those candidates by checking their bounding box coordinates relative to the bounding box of heading. The element whose bounding box is directly below the heading’s box is returned.
Supported Relationship Methods
| Method | Description |
|---|---|
above() | Element is positioned above the reference. |
below() | Element is positioned below the reference. |
toLeftOf() | Element is to the left of the reference. |
toRightOf() | Element is to the right of the reference. |
near() | Element is within a configurable distance of the reference. |
Limits and Common Mistakes
- Browser Support: Relative locators are only available in Selenium 4+. Using them with Selenium 3 or older will throw
NoSuchMethodError. - Driver Compatibility: All major drivers (ChromeDriver, GeckoDriver, EdgeDriver) support the feature, but older driver binaries may not. Always match the driver version to your browser and Selenium version.
- Layout Engine Dependency: The algorithm relies on the browser’s layout engine to compute element coordinates. Results can differ between Chrome, Firefox, and Edge, especially on responsive designs.
- Hidden or Off‑Screen Elements: Elements that are not rendered (e.g., inside a collapsed accordion) will not be found because they have no bounding box.
- Dynamic Content: If the page layout changes after the reference element is located (e.g., due to an AJAX call), the relative positioning may shift. Use explicit waits or re‑locate the reference before applying the relative locator.
- Overly Broad Queries: Using
RelativeLocator.with(By.tagName("div"))can return many candidates. Narrow the base selector (e.g., by class or data attribute) to improve performance and reliability.
Best Practices and Verification
- Always wait for the reference element to be visible before using a relative locator.
- Combine multiple spatial conditions when necessary:
RelativeLocator.with(By.tagName("button")).below(ref).toRightOf(ref2). - After locating the element, verify it by printing its text or taking a screenshot:
System.out.println("Button: " + btn.getText()); // Optionally take a screenshot File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("screenshot.png")); - Use a try‑catch block to handle
NoSuchElementExceptionand log useful diagnostic information. - When writing reusable tests, encapsulate the relative locator logic in a helper method that accepts the reference locator as a parameter.
Conclusion
Relative locators provide a concise way to find elements based on their spatial relationship to other elements, reducing the need for brittle absolute XPaths. By following the setup steps, using explicit waits, and being aware of layout‑engine quirks, you can integrate this feature into your Selenium 4 test suite with confidence.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.