Selenium 4 Relative Locators: A Practical Solution for Brittle UI Tests
Selenium 4’s relative locators let you find elements by their position relative to others, solving brittle CSS selector problems. This blog walks through a concrete example, discusses trade‑offs, and offers actionable next steps for your test suite.
20 Dec 2025, 21:48 UTC

Why Your Tests Break When Themes Change
In many e‑commerce sites the “Add to Cart” button is rendered next to the product title, but its CSS class is theme‑dependent. A test that relies on a hard‑coded class will fail whenever the UI theme is updated, even though the button’s position relative to the title stays the same. The root cause is a brittle selector that ties the test to the visual style rather than the page structure.
Enter Relative Locators
Starting with Selenium 4, the By.locator() API lets you locate elements by their spatial relationship to other elements: below, above, toRightOf, toLeftOf, and near. These selectors are resolved by the browser driver against the current DOM layout, so they do not depend on CSS classes or deep XPath chains.
How It Works
The API builds a query that the driver translates into a visual search. For example, By.locator().below(By.cssSelector("h2.product-title")) asks the driver to find the first element that appears below the element matched by the CSS selector. The driver then returns the matched element, which can be further refined with findElement or findElements.
Worked Example: Finding an “Add to Cart” Button
Assume the page structure looks like this (simplified):
<h2 class="product-title">Widget</h2>
<div class="controls">
<button class="btn btn-primary theme‑1">Add to Cart</button>
</div>
With a theme change, the button’s class becomes btn btn-primary theme‑2. The relative locator keeps the test stable:
// Java – Selenium 4
WebDriver driver = new ChromeDriver();
// Navigate to product page
driver.get("https://example.com/product/123");
// Wait for the product title to be visible
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("h2.product-title")));
// Locate the button that is below the product title
WebElement addToCart = driver.findElement(
By.locator().below(By.cssSelector("h2.product-title")).and(By.tagName("button"))
);
// Click the button
addToCart.click();
Key points:
By.locator().below(...)is executed by the driver, not by Java, so it reflects the actual rendered layout.- Using
and(By.tagName("button"))narrows the result to the button element in case there are multiple tags below the title. - A
WebDriverWaitensures the title is present before the relative search runs, guarding against dynamic content.
Trade‑offs and Limitations
- Layout dependence: If the page layout changes (e.g., a banner is added above the title), the relative relationship shifts and the locator may return a different element or none at all.
- Driver support: All current major drivers (ChromeDriver, GeckoDriver, EdgeDriver) support the four primary directions, but older or custom drivers may ignore them.
- Performance: Relative locators add a small overhead because the driver must compute the visual position of elements. For most tests this is negligible, but it can add up in very large test suites.
- Dynamic content: Elements that load asynchronously after the page render may not be found unless waits are applied.
Practical Next Steps
- Pick a small, stable page in your project and replace a brittle CSS selector with a relative locator.
- Run the test with and without a wait to observe the difference in reliability.
- Integrate the relative locator into your Page Object Model as a method that returns the element, keeping the locator logic encapsulated.
- For critical actions, add a fallback strategy: first try the relative locator, and if it fails, fall back to a CSS selector based on visible text.
- Document the relationship in your test case so future maintainers understand why a relative locator was chosen.
By shifting from style‑dependent selectors to layout‑based ones, you reduce maintenance overhead when themes evolve, while keeping tests readable and aligned with the page’s visual intent.
Conclusion
Relative locators are a powerful addition to Selenium 4 that help you write tests that mirror human navigation: “click the button below the title”. They are not a silver bullet, but when used judiciously in stable UI regions, they can dramatically lower the churn caused by cosmetic changes.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.