The Katalon Blog

Relative Locators in Selenium: Types and Examples

Written by Vincent N. | Sep 24, 2025 8:00:00 PM

Relative Locators in Selenium allow you to pinpoint web elements based on where they appear in relation to other elements. Instead of relying only on IDs or classes, you can now describe elements just like a human would: "this field is below the username," or "that button is to the right of the product name."

These locators are especially useful in dynamic layouts where attributes change frequently. They make your test scripts more readable, easier to maintain, and more resilient across UI updates. Whether you’re working on form validations or product pages, relative locators can simplify your automation workflow.

In this article, we’ll explore:

  • What are Relative Locators in Selenium?
  • How Selenium 4 introduced native support for them
  • Real project use cases and best practices
  • Common pitfalls and how to troubleshoot them
  • How Katalon makes relative locator testing even easier

Let’s get started!

What are Relative Locators?

Relative locators in Selenium help you find page elements by describing their position relative to other elements. Instead of relying on attributes like ID or class, you can say an element is “above” another, “below” it, “toLeftOf”, “toRightOf”, or even “near” it. It mirrors the way you might explain things in real life.

Imagine looking for a new cafe in a busy neighborhood. You might say “the cafe is right next to the bakery.” That simple description gets you there fast. In Selenium tests, relative locators work the same way. You tell the script to look for an element in relation to something familiar on the page.

These locators also make scripts easier to read and maintain. When UI structure shifts slightly, your test can still find the right element based on its position. It keeps your automation flow strong and easy to follow for anyone on your team.

Relative Locators in Selenium 4

Selenium 4 brought in a useful feature: relative locators in Selenium are now a built-in part of the API. Before Selenium 4, testers often relied on complex XPath or custom scripts to work around missing element identifiers. Now it is much simpler and more intuitive to locate elements.

Here are the five core methods introduced:

  • above(): finds an element located above a known reference element
  • below(): finds an element located below a reference element
  • toLeftOf(): finds an element to the left of another element
  • toRightOf(): finds an element to the right of another element
  • near(): finds an element within a certain pixel distance (often ~50 px) of a reference element.

These relative locators were not present in Selenium 3. In earlier versions you needed custom logic or complex XPath to handle spatial relationships. Selenium 4 makes these methods first-class, making your test code more human-readable and easier to maintain.

Advantages of Relative Locators in Selenium

Relative locators in Selenium add clarity to your test scripts. They bring real advantages that simplify both automation and collaboration.

  • Improved readability
    When your script says “click the button below the login field,” it reads just like a manual test instruction. This helps everyone understand the script, no matter their technical level.
  • Resilience in dynamic UIs
    Web apps evolve. Relative locators help your tests adapt without constant updates, even when IDs or classes shift.
  • Human-like interaction
    Just like pointing at something “next to” or “below” another thing, these locators mirror how users actually interact with interfaces.
  • Reduced complexity
    You write less XPath. You avoid complex CSS selectors. You spend more time writing useful tests and less time fixing brittle code.
  • Better collaboration
    When QA teams and developers speak the same language, things move faster. Relative locators bridge that gap with language everyone can follow.

Limitations of Relative Locators in Selenium

Relative locators in Selenium offer clarity and flexibility. They let you describe elements by position, which works well in many real-world scenarios. Still, knowing their limits helps you write more robust tests.

  • Ambiguity when multiple elements match
    If several elements meet the same spatial condition, Selenium may pick the first one. That can happen when two similar fields sit below the same label. To improve precision, refine the reference element or add another locator condition.
  • Overlapping elements may confuse Selenium
    When UI elements overlap, the bounding rectangles may not line up clearly. This can lead to Selenium missing the correct element. Always confirm that the target is visible and layered correctly.
  • Layout changes in responsive designs
    UI elements shift positions across screen sizes. That can alter spatial relationships. Use explicit waits, validate the DOM layout, and pair relative locators with stable attributes in flexible designs.
  • Performance overhead in large DOMs
    Under the hood, Selenium uses page rendering and element bounds to compute location. That can take extra time in large or complex DOM structures. Use relative locators thoughtfully, especially in test suites with many elements.

Relative locators work best when they complement, rather than replace, traditional strategies like ID or CSS. Testing a locator before adding it to your suite ensures it targets the intended element with confidence.

Common Use Cases of Relative Locators in Real Projects

Relative locators in Selenium prove their value in real-world workflows. They help you target elements based on their logical position. That keeps tests simple yet effective in constantly changing UIs.

  • Login forms
    You can find the password field below the username input. This is helpful when the password field lacks unique attributes yet appears consistently under its label.
  • Product listings
    When your script selects the price shown below a product name, it maintains context even if IDs are auto-generated. It stays accurate across product changes.
  • Form validation
    Error messages often show up near the related input field. You can locate those validation hints by using their position relative to the input element.
  • Dashboards
    On analytic pages, you might find status indicators or charts beside labels or icons. Relative locators help keep your tests aligned with layout logic instead of brittle selectors.

These scenarios show how relative locators in Selenium reduce dependency on brittle attributes. Your automation flow becomes clear and more resilient. That leads to broader coverage with less maintenance effort.

Relative Locators vs Traditional Locators

Choosing the right locator improves both performance and maintainability. Relative locators in Selenium and traditional locators each bring unique advantages to automation. Here's how they compare:

Aspect Traditional Locators Relative Locators
Stability Most stable when using unique IDs Reliable when IDs or classes vary
Readability Less readable in long XPath expressions Easier to read and write
Maintainability More updates needed in dynamic UIs Less affected by layout shifts
Flexibility Best for complex queries with XPath or CSS Ideal for spatial relationships between elements

Relative locators in Selenium simplify tests when unique attributes aren't available. Traditional locators provide strong performance when working with fixed identifiers. For the best outcome, use stable locators like ID first. Then combine or switch to relative locators when your UI changes frequently or lacks consistent identifiers.

How to use Relative Locators in Selenium: Example

Working with relative locators in Selenium follows a clear pattern. First, identify the reference element. Then apply the spatial method you need. Finally, interact with the element you're targeting. Here's a practical demonstration using both Java and Python.

Step 1: Identify the reference element, such as a label or button that stays stable in the layout.

Step 2: Use a relative method like below() or toRightOf() to locate the target.

Step 3: Interact with the element as you would with any standard locator.

Here’s how this works in Java:

Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import static org.openqa.selenium.support.locators.RelativeLocator.with;

WebDriver driver = new ChromeDriver();
driver.get("https://katalon.com");

WebElement referenceElement = driver.findElement(By.id("username"));
WebElement passwordField = driver.findElement(with(By.tagName("input")).below(referenceElement));
passwordField.sendKeys("myPassword");

And here’s the same logic using Python:

Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.relative_locator import locate_with

driver = webdriver.Chrome()
driver.get("https://katalon.com")

reference_element = driver.find_element(By.ID, "username")
password_field = driver.find_element(locate_with(By.TAG_NAME, "input").below(reference_element))
password_field.send_keys("myPassword")

Always test your relative locators to ensure they point to the intended elements. This practice guarantees your test logic works exactly as expected across layouts and updates.

Chaining Relative Locators

Chainable relative locators in Selenium let you target elements with precision. You can combine spatial rules like “to the right of” and “below” to narrow down your selection. This makes your locator logic more accurate and less prone to ambiguity.

Use chaining when a single spatial descriptor may match multiple elements. It helps improve test accuracy by refining the search based on two spatial references.

Here is an example in Java illustrating chaining of relative locators:

Java
import static org.openqa.selenium.support.locators.RelativeLocator.with;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

WebDriver driver = new ChromeDriver();
driver.get("https://katalon.com");

WebElement productName = driver.findElement(By.cssSelector(".product-title"));
WebElement priceTag = driver.findElement(with(By.tagName("span"))
    .toRightOf(productName)
    .below(driver.findElement(By.cssSelector(".product-image"))));

Here is the equivalent example in Python:

Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.relative_locator import locate_with

driver = webdriver.Chrome()
driver.get("https://katalon.com")

product_name = driver.find_element(By.CSS_SELECTOR, ".product-title")
price_tag = driver.find_element(
    locate_with(By.TAG_NAME, "span")
    .to_right_of(product_name)
    .below(driver.find_element(By.CSS_SELECTOR, ".product-image"))
)

Chaining multiple spatial rules helps your locator stay precise as the UI evolves. Use chaining wisely and avoid overly complex combinations. That keeps your test logic clear and maintainable.

Troubleshooting Relative Locators

Relative locators in Selenium make tests more intuitive, but real-world layouts can still challenge them. When issues arise, a clear debugging approach helps you stay confident in your automation logic.

  • Wrong element chosen: When Selenium selects the wrong target, refine your reference element. You can choose a closer neighbor or add an additional locator like ID or class to ensure precision.
  • Overlapping elements: If elements layer on top of each other, visibility may confuse the locator. Confirm that the target is visible and not hidden behind another element. Visual validation or simple scripts can help confirm accuracy.
  • Dynamic layouts: Responsive designs shift element positions. Pair relative locators with explicit waits to allow layout to settle. Verify the DOM structure before interacting with an element.
  • Ambiguity with “near()”: The near() locator finds elements close to a reference, which may match multiple candidates. Use it with care and combine with other strategies like tag or class to narrow scope.

Effective debugging includes confirming that your relative locator points at the intended element. Try logging its attributes or visually checking the page. This helps avoid false positives and keeps your test suite reliable.

Best Practices for Using Relative Locators

Relative locators in Selenium unlock powerful ways to reference elements visually. Following a few focused habits ensures they work consistently across your tests.
  • Use when unique IDs are not available: Start with stable locators like ID or Name. When those are missing, relative locators offer a clean fallback that mimics how users navigate a page.
  • Choose stable reference elements: The accuracy of a relative locator depends on its anchor. Always select elements with a consistent presence and position across sessions.
  • Be selective with near(): Use near() when you are confident there is only one nearby match. Pair it with tags or class names to sharpen its precision in crowded layouts.
  • Combine with waits for reliability: Dynamic content may shift position during page load. Explicit waits ensure the layout is ready before locating the target element.
  • Centralize your locator logic: Store all locator strategies in one location. This makes updates fast and consistent when UI changes happen, improving long-term test maintainability.

Good locator design always contributes to robust and readable test scripts. With these habits, relative locators in Selenium become an asset in every test scenario.

How Katalon Simplifies Relative Locator Testing

Katalon is built on top of Selenium and designed to make automation faster, easier, and more scalable. It takes the power of relative locators in Selenium and wraps it in a platform that is visual, intelligent, and team-friendly.

Instead of hardcoding every locator into your test script, you can rely on Katalon's Visual Object Repository. It stores and manages web elements in one place. Updates become simple, even when the UI evolves.

Katalon also includes Built-in Test Management and Reporting. Your test results are tracked automatically. You get instant feedback on failures, environment logs, and detailed reports that help guide improvements.

The platform comes with AI-Assisted Locator Strategies. When elements change in structure or attribute, the AI engine finds the closest match and heals broken locators automatically. This keeps your relative locator tests running without interruption.

With Cloud Grid Integration, you can execute test cases across multiple browsers and platforms. There is no need to manage infrastructure manually. It scales as your test needs grow.

Teams that value precision and speed will find Katalon a natural fit. It reduces complexity without limiting flexibility. With less scripting and more visibility, Katalon helps you bring the full potential of relative locators to your projects.

Cross-Browser Behavior of Relative Locators

Relative locators in Selenium offer flexibility and readability. Their behavior is generally consistent across modern browsers because Selenium handles many differences internally. Still, layout rendering can vary slightly between browsers, which may influence how elements are positioned on the page.

For instance, Chrome and Firefox may interpret padding or margins differently in complex layouts. Safari and Edge sometimes apply spacing and float rules in unique ways. These differences can shift element positions by a few pixels. Even small variations may influence which element is selected using methods like near().

To ensure accuracy, test your relative locator scripts in all supported browsers. This confirms that elements are identified correctly regardless of layout rendering nuances. Selenium makes it simple to switch drivers, so you can cover more environments with minimal changes.

Cross-browser testing also helps uncover edge cases early. You can avoid surprises during production releases by validating locator precision in advance. Relative locators are reliable, but verifying their behavior across platforms builds confidence in every test run.

How Katalon Simplifies Relative Locator Testing

Katalon is a powerful low-code automation platform that extends Selenium’s capabilities. It provides an easier, more scalable way to apply relative locators in real-world projects. Built on top of Selenium, it brings structure, automation flexibility, and intelligent features that reduce scripting effort.

Katalon improves locator testing through several purpose-built tools:

  • Visual Object Repository: manage locators visually in one central place. This makes them easy to update, search, and reuse without manually editing scripts.
  • Built-in Test Management & Reporting: view results instantly, connect test cases with reports, and optimize test cycles using insights and logs.
  • AI-Assisted Locators: enable dynamic locator healing when web elements change. This ensures that tests keep running smoothly even when the DOM shifts.
  • Integration with Cloud Grids: run relative locator tests across thousands of browser and OS combinations in the cloud. No extra configuration needed.

With these features, teams can confidently build and maintain tests that use relative locators in Selenium. Katalon fits seamlessly into both agile and enterprise workflows. It helps testers focus on outcomes instead of script complexity.

To get started, explore the resources at Katalon Academy for learning paths and tutorials. You can also dive into Katalon Docs for technical implementation guides and examples.