Relative Locators in Selenium: Types and Examples

May 19, 2026 · 10 min read · Tool Comparison

Blog / Insights /
Relative Locators in Selenium: Types and Examples

Relative Locators in Selenium: Types and Examples

QA Consultant Updated on

Learn with AI

Linkedin

Facebook

X (Twitter)

Mail

Learn with AI

Relative locator in Selenium allow you to pinpoint web elements found on where they seem in relative to other elements. Instead of relying only on IDs or classes, you can now describe elements simply like a human would: `` this field is below the username, '' or `` that button is to the right of the product gens. ''

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

In this article, we ’ ll explore:

  • What are Comparative Locators in Selenium?
  • How Selenium 4 introduced native support for them
  • Real task use cause and best pattern
  • Common pitfalls and how to trouble-shoot them
  • How Katalon makes comparative locator test even easier

Let ’ s get started!

What are Relative Locators?

Comparative locators in Seleniumhelp you find page factor by line their position relative to other constituent.

Instead of trust on attributes like ID or class, you can say an constituent is “ above ” another, “ below ” it, “ toLeftOf ”, “ toRightOf ”, or yet “ near ” it. It mirrors the way you might excuse things in real living.

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

These locater also make scripts easy to read and conserve. When UI construction displacement slightly, your test can still find the right element based on its place. It keep your automation flow strong and easygoing to postdate for anyone on your squad.

Relative locators in Selenium 4

Selenium 4 brought in a utile lineament:proportional locators in Seleniumare now a built-in part of the API. Before Selenium 4, testers often relied on complex XPath or usage script to work around missing element identifiers. Now it is much simpler and more nonrational to site constituent.

Here are the five core method present:

  • above(): encounter an factor located above a known reference ingredient
  • below(): regain an element located below a reference constituent
  • toLeftOf (): finds an element to the left of another ingredient
  • toRightOf (): finds an element to the right of another element
  • near(): finds an constituent within a sure pel distance (often ~50 px) of a mention element.

These relative locators were not present in Selenium 3. In earliest edition you necessitate custom logic or complex XPath to handle spatial relationships. Selenium 4 makes these methods first-class, making your test codification more human-readable and easier to preserve.

Advantages of relative locators in Selenium

Relative locater in Selenium add limpidity to your test hand. 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 facilitate everyone realise the script, no matter their technical level.
  • Resilience in dynamic UIs:Web apps evolve oftentimes. Relative locators help your tests adapt without ceaseless update, even when IDs or family shift.
  • Human-like interaction:Just like pointing at something “ next to ” or “ below ” another thing, these locator mirror how users actually interact with interfaces.
  • Reduced complexity: & nbsp;You pen less XPath. You forfend complex CSS selectors. You spend more time writing utile examination and less time fixing brittle code.
  • Better collaboration:When QA teams and developers speak the same speech, thing move quicker. Comparative locators bridge that gap with lyric everyone can follow.

Limitations of Relative Locators in Selenium

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

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

  • Ambiguity when multiple elements match:If various elements meet the like spacial condition, Selenium may pick the first one. That can happen when two similar fields sit below the same label. To better preciseness, down the reference element or add another locator status.
  • Overlapping elements may confuse Selenium:When UI elements overlap, the bounding rectangles may not line up clearly. This can lead to Selenium missing the right factor. Always corroborate that the mark is visible and layered correctly.
  • Layout changes in responsive designs:UI elements shift place across screen sizes. That can alter spatial relationships. Use explicit waits, corroborate the DOM layout, and pair comparative locator with stable attributes in flexible designs.
  • Performance overhead in large DOMs:Under the hood, Selenium uses page interpretation and element bounds to compute locating. That can guide extra time in large or complex DOM structures. Use relative locators thoughtfully, specially in test suites with many element.

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

Common use suit of relative locators in real projects

Relative locator in Seleniumevidence their value in real-world workflows. They help you place factor free-base 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 lack unique attributes yet appears consistently under its label.
  • Product list
    When your script selects the damage shown below a product gens, it maintains context even if IDs are auto-generated. It stays accurate across product changes.
  • Form validation
    Error messages often evidence up near the related input field. You can locate those validation hints by using their position relative to the input element.
  • Dashboards
    On uninflected Page, you might detect condition indicators or charts beside label or icons. Relative locators facilitate continue your tryout aligned with layout logic instead of brittle selector.

These scenarios show howcomparative locators in Seleniumcut dependance on brittle attributes. Your mechanization flow turn clear and more resilient. That leads to broader coverage with less maintenance effort.

Comparative locators vs Traditional locater

Choosing the right locater improves both performance and maintainability.Comparative locators in Seleniumand traditional locators each bring unequaled advantages to automation. Here 's how they compare:

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

Comparative locators in Seleniumsimplify exam when unique attributes are n't available. Traditional locator supply strong performance when working with fixed identifiers. For the good event, use stable locators like ID first. Then cartel or shift to relative locators when your UI modification frequently or lacks reproducible identifier.

How to use relative locater in Selenium?

Working withproportional locators in Seleniumfollows a open pattern. First, name the reference element. Then apply the spatial method you need. Finally, interact with the element you 're targeting. Here 's a practical presentation using both Java and Python.

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

Step 2:Use a comparative method likebelow()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; importee org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import stable 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 hither ’ s the same logic using Python:

Python
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.relative_locator meaning 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 level to the intended elements. This drill guarantees your test logic work exactly as await across layouts and update.

Chaining comparative locators

Chainable proportional locator in Selenium let you target elements with preciseness. You can combine spatial rules like “ to the right of ” and “ below ” to specify down your option. This makes your locator logic more exact and less prone to equivocalness.

Use chaining when a single spatial descriptor may mate multiple elements. It help improve test accuracy by refining the hunting based on two spatial reference.

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

Java
significance static org.openqa.selenium.support.locators.RelativeLocator.with; import org.openqa.selenium.By; importation org.openqa.selenium.WebDriver; signification 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 significance webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.relative_locator importee 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, `` duad '') .to_right_of (product_name) .below (driver.find_element (By.CSS_SELECTOR, `` .product-image '')))

Chaining multiple spacial convention helps your locator stoppage precise as the UI evolves. Use chaining sagely and avoid excessively complex combinations. That keep your test logic clear and maintainable.

Troubleshooting proportional locators

Relative locators in Seleniumdo exam more intuitive, but real-world layout can still challenge them. When issues arise, a open debugging approaching helps you abide positive in your mechanization logic.

  • Wrong element chosen:When Selenium selects the improper target, refine your mention factor. You can select a finisher neighbor or add an additional locater like ID or class to ensure preciseness.
  • Overlapping elements:If elements layer on top of each other, visibility may fuddle the locator. Confirm that the quarry is visible and not hidden behind another element. Visual validation or uncomplicated handwriting can aid sustain truth.
  • Dynamic layouts:Responsive designs shift element position. Pair relative locater with expressed waits to allow layout to settle. Verify the DOM structure before interacting with an element.
  • Ambiguity with “ near () ”:The near () locater finds constituent close to a reference, which may match multiple candidates. Use it with tending and combine with other strategy like tag or class to narrow range.

Efficacious debugging includes confirming that your relative locator points at the intended constituent. Try logging its attributes or visually checking the page. This helps avoid mistaken positives and proceed your test suite reliable.

Better practices for using relative locators

Relative locators in Seleniumunlock potent ways to reference factor visually. Following a few focused habits ensure 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, proportional locators offer a clean disengagement that mimics how users pilot a page.
  • Choose stable reference elements:The accuracy of a relative locater depends on its keystone. Always select ingredient with a ordered presence and position across sessions.
  • Be selective with near ():Use near () when you are confident there is only one nearby match. Pair it with tatter or stratum names to sharpen its precision in herd layout.
  • Combine with waits for reliability:Dynamic substance may shift position during page load. Explicit waits ensure the layout is ready before locating the target element.
  • Centralize your locater logic:Store all locator strategy in one location. This do updates fast and consistent when UI changes happen, amend long-term trial maintainability.

Full locator design always contributes to robust and readable test scripts. With these habits,relative locators in Seleniumturn an plus in every test scenario.

How Katalon simplify relative locator examine

Katalon is built on top of Selenium and designed to make mechanization faster, easy, and more scalable. It direct the ability of comparative locators in Selenium and roll it in a platform that is optical, levelheaded, and team-friendly.

  • Instead of hardcoding every locator into your tryout script, you can rely on Katalon 'sOcular Object Repository. It stores and manages web component in one place. Updates become simpleton, even when the UI evolves.
  • Katalon likewise includesBuilt-in Test Management and Reporting. Your test results are tracked automatically. You get inst feedback on failures, environs logarithm, and detailed reports that supporter take improvements.
  • The platform come withAI-Assisted Locator Strategies. When elements change in structure or attribute, the AI locomotive finds the closest match and heals broken locators automatically. This hold your relative locater tests running without interruption.
  • With Cloud Grid Integration, you can execute exam instance across multiple browsers and platforms. There is no need to manage infrastructure manually. It scales as your test needs grow.

In little, Katalon makes Selenium more productive. It offers the power of automation in a scalable, team-friendly package that grows with your projects.

📝 Want to explore what Katalon can do for your team?Request a demoto see how it aid teams automatise faster with less attempt.

Explain

|

Vincent N.
QA Consultant
Vincent Nguyen is a QA adviser with in-depth domain knowledge in QA, software testing, and DevOps. He has 5+ years of experience in craft content that resonate with techies at all tier. His involvement sweep from writing, technology, to establish cool clobber.

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free