Using Selenium 4 Relative Locators to Find Elements by Visual Proximity
Learn how Selenium 4’s Relative Locators let you find elements by their visual position relative to a stable reference, with a concrete Java example, trade-offs, and verification tips.
07 Jan 2026, 17:57 UTC

Problem: locating elements when IDs change but visual order stays the same
In many web applications, form fields are generated with dynamic IDs or data attributes that change on each page load. Relying on those attributes makes tests brittle. Yet the visual relationship between fields often remains stable—for example, the “Last Name” input is always rendered below the “First Name” input. Selenium 4 introduced Relative Locators to let you express that relationship directly in code.
How Relative Locators work
Relative Locators are built on the org.openqa.selenium.support.locator.RelativeLocator class (Java) or the equivalent in other language bindings. You start with a base criterion such as tag name, class, or name, then refine it with spatial terms: above, below, toLeftOf, toRightOf, or near. The resolver evaluates the DOM position of the reference element and returns the first matching element that satisfies the spatial constraint.
Key requirements
- Selenium 4.0 or later.
- A browser driver that implements the W3C WebDriver spec (Chrome, Firefox, Edge, etc.).
- The reference element must be uniquely identifiable by a stable locator (ID, name, etc.).
Worked example: finding the “Last Name” field below “First Name”
Assume a simple login form where the first name field has a stable name attribute, but the last name field’s ID is generated.
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.locator.RelativeLocator;
public class RelativeLocatorDemo {
public static void main(String[] args) {
// Set up the driver – adjust to your chromedriver setup as needed
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com/login-form");
// 1. Locate the reference element with a stable attribute
WebElement firstName = driver.findElement(By.name("firstName"));
// 2. Build a Relative Locator: find an input below the first name field
WebElement lastName = driver.findElement(
RelativeLocator.withTagName("input")
.below(firstName)
);
// 3. Interact with the located element
lastName.sendKeys("Doe");
System.out.println("Last name entered successfully");
} finally {
driver.quit();
}
}
}
Where to run: Execute the main method in your IDE or via mvn test if you integrate it into a Maven project. No special OS permissions are required beyond the ability to launch the browser driver. Replace the placeholder URL and the firstName attribute with values from your actual page.
Expected check: After sendKeys, assert that the field’s value matches what you typed, e.g., assertEquals("Doe", lastName.getAttribute("value"));. If the assertion fails or a NoSuchElementException is thrown, the locator did not resolve to the intended element.
Trade-offs and limitations
Relative Locators are powerful but not a silver bullet.
- Dependency on DOM order: The resolver uses the element’s position in the rendered DOM, not raw pixel coordinates. CSS flexbox or grid reordering, absolute positioning, or transforms that change spatial relationships can cause false positives or negatives.
- Performance impact: Each relative lookup may trigger additional DOM queries to compute the spatial relationship, adding overhead per lookup. In large suites this is usually negligible, but it is worth profiling if you have thousands of such locators.
- Reference element must be unique: If the element you base the relationship on is not uniquely identifiable, the locator may resolve against the wrong reference, leading to unpredictable results.
Practical way to verify the assumption
Before committing to a Relative Locator, inspect the page in the browser’s developer tools:
- Right-click the reference element and choose “Inspect”.
- Note its DOM position relative to the target element.
- Toggle any CSS that might reorder elements (flex direction, order property, absolute positioning) and observe whether the rendered relationship changes.
- Re-run the test across the browsers you support to confirm consistent resolution.
If the spatial relationship stays constant across the states you care about, the Relative Locator is likely stable.
Closing: when to reach for Relative Locators
Use Relative Locators when:
- You have a stable anchor element (unique ID, name, aria-label, etc.).
- The visual relationship between the anchor and the target is unlikely to change across responsive breakpoints or theme switches.
- You want to improve test readability and reduce reliance on fragile generated attributes.
If the layout is highly dynamic or you frequently adjust CSS that repositions elements, pair Relative Locators with a fallback to a more robust locator (e.g., a data-test attribute) or consider adding stable IDs to the markup.
By combining a solid reference element with the spatial semantics of Relative Locators, you can write clearer, more maintainable Selenium tests—while keeping an eye on the layout constraints that make them work.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.