Selenium Relative Locators

Relative locators find an element by describing where it sits compared with a neighbor. People give directions the same way: the pharmacy is left of the bank and above the bakery. Selenium 4 introduced this feature, and it reads almost like a spoken sentence. The tool measures the screen position of each element and returns the one that matches your description.

Why They Help

Some pages have no helpful id or class. A form might hold ten identical text boxes where only a label tells them apart. Relative locators use that label as an anchor. You skip long and fragile XPath strings.

Five Direction Methods

MethodMeaning
above(element)Target sits higher on screen
below(element)Target sits lower on screen
toLeftOf(element)Target sits on the left side
toRightOf(element)Target sits on the right side
near(element)Target sits within 50 pixels

Map Diagram

+------------------------------------------+
|  [ Email label ]      [ Email box ]      |
|                                          |
|  [ Password label ]   [ Password box ]   |
|                                          |
|              [ Cancel ]  [ Login ]       |
+------------------------------------------+

Password box = toRightOf(Password label)
Email box    = above(Password box)
Login button = toRightOf(Cancel button)

Basic Syntax

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

WebElement passwordLabel = driver.findElement(By.id("pwdLabel"));
WebElement passwordBox = driver.findElement(
        with(By.tagName("input")).toRightOf(passwordLabel));
passwordBox.sendKeys("secret123");

The with() method starts with a regular locator, here the tag name, and narrows the result using the direction.

Chaining Directions

You can stack several directions to shrink the match list. Each added rule removes candidates that fail the test.

WebElement target = driver.findElement(
        with(By.tagName("input"))
        .below(emailBox)
        .above(loginButton)
        .toRightOf(passwordLabel));

Real Scenario: Seat Selection

A cinema page shows seats in rows. Every seat button looks identical. You anchor on the seat labeled A5 and ask for the seat to its right.

Row A:  [A3] [A4] [A5] [A6] [A7]
                   ^     ^
              anchor     target = toRightOf(A5)
WebElement a5 = driver.findElement(By.id("seat-A5"));
driver.findElement(with(By.tagName("button")).toRightOf(a5)).click();

Limits to Remember

  • Layout drives the result. A different screen size can change the answer.
  • Hidden elements still count in some cases, which gives surprise matches.
  • The near() method uses a fixed range of 50 pixels unless you pass a custom value.
  • Strong ids and names remain faster and steadier than relative locators.

Best Use Guide

SituationRecommended Choice
Element has a unique idBy.id
Repeated inputs with labelsRelative locator
Grid of identical buttonsRelative locator with anchor
Complex nested structureXPath or CSS selector

Key Points

  • Relative locators describe position, not structure.
  • Anchor elements should have stable locators.
  • Chain two or three directions for precise results.
  • Test them at the same window size every run.

How Selenium Calculates Position

Selenium asks the browser for the bounding box of every candidate element. A bounding box is the invisible rectangle that surrounds an element, defined by its top, bottom, left, and right edges. The tool compares your anchor rectangle with each candidate rectangle. An element passes the above() test when its bottom edge sits higher than the anchor's top edge. Left and right tests use the side edges in the same way.

Anchor box:        Candidate box:
+---------+        +---------+
| anchor  |        | target  |   target.bottom < anchor.top
+---------+        +---------+   so target passes above()

Custom Distance with near()

The near() method accepts a second value that sets the pixel distance. A small number gives a strict search, and a large number widens the net.

WebElement hint = driver.findElement(
        with(By.tagName("span")).near(emailBox, 80));

Debugging Tips

Check Window Size

A narrow window can push elements into a single column, which changes every direction. Set the window size at the start of each test.

Print Matches

Use findElements with the relative locator and print the list size. A result of zero or more than one signals a weak anchor.

Pick Close Anchors

Choose an anchor that sits right beside the target. A distant anchor increases the risk that another element slips between them.