Relative Locators in Selenium

Learn how to use relative locators in Selenium 4. Run Selenium tests on real devices with BrowserStack instead of investing in an in-house Selenium Grid.

Guide Banner Image
Home Guide Relative Locators in Selenium

Relative Locators in Selenium

Relative Locators are one of the standout features introduced in Selenium 4, designed to make element identification more intuitive. They allow you to locate web elements based on their visual position relative to other elements on the page.

Overview

What are Relative Locators? 

Relative locators (also called friendly locators) help find elements by describing their position in relation to nearby elements. This is especially useful when elements lack unique attributes like IDs or names but are consistently placed in the layout.

Types of Relative Locators in Selenium 4

Selenium 4 introduces five built-in relative locators:

  • above(element): Finds an element located above the specified element.
  • below(element): Finds an element located below the specified element.
  • toLeftOf(element): Finds an element to the left of the specified element.
  • toRightOf(element): Finds an element to the right of the specified element.
  • near(element): Finds an element near (within ~50 pixels) of the specified element.

This article explains the primary relative locators in Selenium 4, including their syntax and how to use them.

What are Relative Locators?

Relative Locators are a feature in Selenium 4 that allow you to identify web elements based on their spatial relationship to other elements. Instead of relying solely on fixed attributes like id, name, or class, you can locate elements by describing their position relative to a nearby element on the page.

For example, if you know the position of a label and want to interact with the input box below it, you can use below() instead of writing a complex XPath. This makes tests more intuitive, readable, and often more resilient to layout changes.

Relative locators are particularly useful when:

  • The target element doesn’t have a reliable locator.
  • The position of elements is consistent in relation to others.
  • You want to write more human-like, maintainable tests.

Relative Locators in Selenium 4

Here are the five relative locators introduced in Selenium 4, which allow you to find elements based on their position relative to other known elements.

1. above()

above() is used to locate the web element(s) just above the specified element.

Syntax:

To locate element(s) that is above a specific locator:

above(By locator)

To locate element(s) that is above a specific web element:

above(WebElement element)

2. below()

below() is used to locate the web element(s) just below the specified element.

Syntax:

To locate element that is below a specific locator:

below(By locator)

To locate element that is below a specific web element:

below(WebElement element)

3. toLeftOf()

It is used to locate the web element(s) present on the left of the specified element.

Syntax:

To locate element that is to the left a specific locator:

toLeftOf(By locator)

To locate element that is to the left a specific web element:

toLeftOf(WebElement element)

4. toRightOf()

It is used to locate the web element(s) present on the right of the specified element.

Syntax:

To locate element that is to the right a specific locator:

toRightOf(By locator)

To locate element that is to the right a specific web element:

toRightOf(WebElement element)

5. near()

It is used to locate the web element(s) located at approximately 50 pixels away from the specified element. The distance can be passed as an argument to an overloaded method

Syntax:

near(By locator)
near(WebElement element)
near(By locator, int atMostDistanceInPixels)
near(WebElement element, int atMostDistanceInPixels)

Advantages of Relative Locators in Selenium

Relative locators in Selenium 4 provide several benefits that enhance both the readability and robustness of automation scripts. Here are the key advantages:

  • More human-readable tests: Test logic becomes easier to understand by describing element positions in a way that mirrors how users visually interpret the UI.
  • Works well when elements lack unique attributes: When elements do not have unique IDs or names, relative locators provide an effective alternative by referencing nearby elements.
  • Reduces reliance on complex XPath expressions: Spatial relationships can be expressed using simple methods instead of lengthy and brittle XPath queries.
  • More resilient to minor layout changes: As long as the relative positions of elements remain unchanged, these locators are less likely to break due to UI modifications.
  • Allows chaining for higher precision: Multiple relative locators can be combined (e.g., below().toRightOf()) to locate elements in complex or tightly packed layouts accurately.

BrowserStack Automate Banner

Limitations of Relative Locators in Selenium

While relative locators improve flexibility and readability in Selenium tests, they also have certain drawbacks.

  • Limited accuracy in complex layouts: In densely packed UIs, relative locators may incorrectly identify nearby elements with inconsistent spacing.
  • Not a complete replacement for traditional locators: Relative locators work best as a fallback or supplement and not as the primary method in all cases.
  • Pixel-based proximity in near(): The near() method uses an approximate pixel value (default ~50px), which can lead to unpredictable results on responsive designs.
  • Depends on visual rendering: Since relative locators rely on the rendered position in the browser, behavior may vary across different screen resolutions or zoom levels.
  • Limited browser support in earlier versions: Older browser drivers or outdated Selenium bindings may not fully support relative locators, leading to compatibility issues.

How to use Relative locators in Selenium: Example

First, it’s important to set up a suitable Selenium environment to understand how relative locators work in practice.

Pre-requisites:

  1. Install Eclipse IDE or any other code editor.
  2. Create a Maven project in Eclipse.
  3. Add the latest Selenium 4 Java dependency to the pom.xml file:
<dependencies>

<dependency>

<groupId>org.seleniumhq.selenium</groupId>

<artifactId>selenium-java</artifactId>

<version>4.11.0</version>

</dependency>

</dependencies>

Relative locators were introduced in Selenium 4.0.0-alpha-3, so ensure the version used is 4.0.0-alpha-3 or newer.

The example below uses the https://www.browserstack.com/ website to showcase how each relative locator functions in the real world.

1. above()

The “Get A Demo” button appears above the “App Live” element in the given layout. When the “Get A Demo” button lacks a unique identifier, Selenium’s above() relative locator can be used to access it by referencing the known location of the “App Live” element.

Follow these steps

Step 1: Identify the reference element (“App Live”) and create a WebElement:

WebElement appLive = driver.findElement(By.cssSelector("a.product-card-app-live"));

Step 2: Next with the help of Eclipse IDE/ any IDE, import the RelativeLocator package and understand the syntax of Relative Locator method.

Type the line of code below:

driver.findElement(RelativeLocator.)

b

Import the RelativeLocator class from Selenium to enable the use of relative locators:

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

Step 3: Use the with method from the RelativeLocator class. This method takes a By locator as its argument:

WebElement getADemo = driver.findElement(RelativeLocator.with(By.tagName("button")));

Using with method of Relative Locator class in Selenium

Step 4: Next, use the relative method (above(), below(), toLeftOf(), toRightOf(), near()) along with the element whose locator is known (App Live element). For that, enter “.” after the “with” method is complete.

relative methods

Then, choose “above(WebElement element)” and by adding the “App Live” locator inside the parentheses, the code looks like below:

WebElement getADemo = driver.findElement(

    RelativeLocator.with(By.tagName("button")).above(appLive)

);

Step 5: Perform the desired action on the located element. For example, clicking the “Get A Demo” button:

getADemo.click();

This helps identify the “Get A Demo” button by its position, even without a unique attribute, enhancing test reliability and readability.

Complete code for Relative Locators above() Example:

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;

public class RLocators {

public static void main(String args[]) throws InterruptedException {

WebDriver driver;

driver = new ChromeDriver();

driver.get("https://www.browserstack.com/");

WebElement appLive = driver.findElement(By.cssSelector("a.product-card-app-live"));

WebElement getADemo = driver.findElement(RelativeLocator.with(By.tagName("button")).above(appLive));

getADemo.click();

}

}

2. below()

When the “Get A Demo” button is placed below a section such as the “Text Section”, the below() relative locator can be used by referencing the element above it.

Example of below() Relative Locator

Example:

WebElement textSection = driver.findElement(By.cssSelector("div.text-section p"));

WebElement getADemo = driver.findElement(

    RelativeLocator.with(By.tagName("button")).below(textSection)

);

getADemo.click();

Complete Code:

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;



public class RLocators {

    public static void main(String args[]) throws InterruptedException {

        WebDriver driver = new ChromeDriver();

        driver.get("https://www.browserstack.com/");



        WebElement textSection = driver.findElement(By.cssSelector("div.text-section p"));

        WebElement getADemo = driver.findElement(

            RelativeLocator.with(By.tagName("button")).below(textSection)

        );

        getADemo.click();

    }

}

3. toRightOf()

The toRightOf() method identifies an element located to the right of another. For instance, the “Get A Demo” button placed to the right of the “Get Started Free” link can be located using this method.

WebElement getStartedFree = driver.findElement(By.cssSelector("a#signupModalButton"));

WebElement getADemo = driver.findElement(

    RelativeLocator.with(By.tagName("button")).toRightOf(getStartedFree)

);

getADemo.click();

4. toLeftOf()

When the target element is positioned to the left of a known element, the toLeftOf() method is suitable. For example, the “Get Started Free” link lies to the left of the “Get A Demo” button.

WebElement getADemo = driver.findElement(

    By.xpath("//button[contains(@class, 'btn-secondary') and text()='Get a demo']")

);

WebElement getStartedFree = driver.findElement(

    RelativeLocator.with(By.tagName("a")).toLeftOf(getADemo)

);

getStartedFree.click();

5. near()

The near() method locates an element that is approximately within 50 pixels of a given reference element. An optional distance can be passed to the overloaded version of this method. The “Search” button is identified near the “Free Trial” link in the following example.

WebElement freeTrial = driver.findElement(

    By.xpath("//ul[@id='primary-menu']//a[@id='free-trial-link-anchor']")

);

WebElement search = driver.findElement(

    RelativeLocator.with(By.tagName("button")).near(freeTrial)

);

search.click();

Complete code for toRightOf() and toLeftOf() and near():

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;

 

public class RLocators {

   public static void main(String args[]) throws InterruptedException {

         WebDriver driver;

         driver = new ChromeDriver();

         driver.get("https://www.browserstack.com/");

         WebElement getStartedFree = driver.findElement(By.cssSelector("a#signupModalButton"));

         WebElement getADemo = driver.findElement(RelativeLocator.with(By.tagName("button")).toRightOf(getStartedFree));

         getADemo.click();

         driver.get("https://www.browserstack.com/");

         driver.manage().window().maximize();

         WebElement getADemoo = driver

                  .findElement(By.xpath("//button[contains(@class, 'btn-secondary') and text()='Get a demo']"));

         WebElement getStartedFreee = driver.findElement(RelativeLocator.with(By.tagName("a")).toLeftOf(getADemoo));

         getStartedFreee.click();

         driver.get("https://www.browserstack.com/");

         WebElement freeTrial = driver

                  .findElement(By.xpath("//ul[@id='primary-menu']//a[@id='free-trial-link-anchor']"));

         WebElement search = driver.findElement(RelativeLocator.with(By.tagName("button")).near(freeTrial));

         search.click();

   }

}

Chaining Relative locators

In some scenarios, using a single relative locator may not provide enough precision to identify a specific element. Selenium 4 allows combining multiple relative locators to create more accurate and reliable selectors. This technique is known as chaining relative locators.

By chaining methods like below(), toRightOf(), or near(), it’s possible to describe an element’s location more specifically based on its relationship to multiple surrounding elements.

Example:

Consider a case where the “Get a Demo” button needs to be located. It appears below the “Text Section” and to the right of the “Get Started Free” link. This can be achieved by chaining the below() and toRightOf() methods.

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;



public class RLocators {

    public static void main(String args[]) throws InterruptedException {

        WebDriver driver = new ChromeDriver();

        driver.get("https://www.browserstack.com/");



        WebElement textSection = driver.findElement(By.cssSelector("div.text-section p"));

        WebElement getStartedFree = driver.findElement(By.cssSelector("a#signupModalButton"));



        WebElement getADemo = driver.findElement(

            RelativeLocator.with(By.tagName("button"))

                .below(textSection)

                .toRightOf(getStartedFree)

        );



        getADemo.click();

    }

}

Using chained relative locators improves test accuracy, especially in layouts where elements are placed close together or lack unique attributes.

How BrowserStack Facilitates Selenium Relative Locator Testing?

BrowserStack is a real device cloud platform that provides access to over 3,500 real browsers and devices. It helps teams validate Selenium 4 relative locators across real-world environments without setting up and maintaining in-house infrastructure.

  • Cloud Selenium Grid: Delivers on-demand browser and device infrastructure, eliminating the need for local lab setup or maintenance.
  • Parallel testing: Enables simultaneous execution of locator-based test scripts across multiple device/browser combinations, ensuring consistent behavior regardless of environment
  • Complete Selenium 4 support: Fully compatible with all five relative locators (above, below, toLeftOf, toRightOf, near), with BrowserStack leading as the first cloud provider to support them
  • Test debugging tools: Offers screenshots, video logs, and DOM snapshots to diagnose spatial relationships, especially useful when relative locators fail due to layout shifts.
  • Cross-browser consistency: Ensures that position-based locators work reliably across Chrome, Firefox, Safari, and Edge within the hosted Cloud Selenium Grid.

Talk to an Expert

Conclusion

Relative locators add another layer of finding elements with above(), below(), toLeftOf(), toRightOf(), and near() locators. It makes locating elements easier when another element’s locator is known. However, it is always advisable to test the website on real devices under real user conditions on different screen resolutions for more accurate results.

BrowserStack real device cloud offers 3500+ real devices and browsers to test the website extensively and provide accurate results under real world conditions. You can run parallel tests using Cloud Selenium Grid where same tests can be run on different devices-browser-OS combinations to tests cross browser compatibility of the website.

Try BrowserStack for Free

Tags
Selenium Selenium Webdriver Website Testing