To Right Of

Introduction

Selenium 4 introduced Relative Locators, a powerful feature that allows automation engineers to locate web elements based on their position relative to other elements on a webpage. Instead of depending entirely on attributes such as ID, Name, or XPath expressions, Relative Locators use an element’s visual position to identify related elements.

The to_right_of() Relative Locator is used to locate an element that appears to the right of another known element on the webpage. This approach is particularly useful when elements do not contain unique attributes but maintain consistent visual relationships.

In this tutorial, you’ll learn what the to_right_of() Relative Locator is, why it is used, its syntax, practical examples, real-world use cases, common mistakes, and best practices.


What is the To Right Of Relative Locator?

The to_right_of() Relative Locator identifies a web element that is positioned to the right of another known element on the webpage.

Instead of locating an element directly, Selenium first identifies a reference element and then searches for matching elements that appear visually to its right.

For example, consider the following webpage layout:

--------------------------------
| [ Left ]        [ Right ]    |
--------------------------------

The Right button is positioned to the right of the Left button.

Selenium can use the Left button as the reference element and locate the Right button using the to_right_of() Relative Locator.


Why Use the To Right Of Relative Locator?

The to_right_of() Relative Locator is useful because it:

  • Locates elements using their visual position.

  • Reduces dependency on complex XPath expressions.

  • Improves locator readability.

  • Supports modern webpage layouts.

  • Improves framework maintainability.

  • Is widely used in Selenium 4 automation frameworks.


Syntax

driver.find_element(
    locate_with(
        By.ID,
        "element"
    ).to_right_of(reference_element)
)

Where:

  • locate_with() → Creates a Relative Locator.

  • By.ID → Defines the locator strategy.

  • to_right_of() → Locates elements positioned to the right of the reference element.

  • reference_element → Previously located web element used as the reference point.


Example

The webpage contains two buttons positioned horizontally. Selenium first locates the Left button and then identifies the Right button positioned to its right.

The Selenium code is:

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


# Topic: 14. Selenium 4 Relative Locators - To Right Of
# Practice site: https://www.testmuai.com/selenium-playground/
# Run: pytest -s 14_examples/test_04_to_right_of.py
#
# The to_right_of() relative locator finds an element to the right of a
# reference element.


def test_relative_locator_to_right_of():
    driver = webdriver.Chrome()

    try:
        driver.get(
            "https://www.testmuai.com/selenium-playground/"
        )

        driver.execute_script(
            """
            const container = document.createElement('div');
            container.style.cssText =
            'display:flex;gap:20px;margin:20px;';

            const left = document.createElement('button');
            left.id = 'left-button';
            left.textContent = 'Left';

            const right = document.createElement('button');
            right.id = 'right-button';
            right.textContent = 'Right';

            container.append(left, right);
            document.body.prepend(container);
            """
        )

        left_button = driver.find_element(
            By.ID,
            "left-button"
        )

        right_button = driver.find_element(
            locate_with(
                By.ID,
                "right-button"
            ).to_right_of(left_button)
        )

        assert right_button.text == "Right"

    finally:
        driver.quit()

Output

The Right button is
located successfully using
the to_right_of() Relative
Locator with the Left
button as the reference
element.

Understanding the Code

Import the Required Classes

from selenium.webdriver.common.by import By

from selenium.webdriver.support.relative_locator import (
    locate_with
)

Imports Selenium’s locator strategies and Relative Locator functionality.

Open the Practice Website

driver.get(
    "https://www.testmuai.com/selenium-playground/"
)

Launches the Selenium practice website.

Create the Buttons Dynamically

driver.execute_script(
    """ JavaScript Code """
)

Uses JavaScript to dynamically create two buttons positioned horizontally on the webpage.

Locate the Left Button

driver.find_element(
    By.ID,
    "left-button"
)

Locates the Left button that will be used as the reference element.

Locate the Right Button

driver.find_element(
    locate_with(
        By.ID,
        "right-button"
    ).to_right_of(left_button)
)

Searches for the Right button positioned to the right of the Left button.

Validate the Element

assert right_button.text == "Right"

Verifies that Selenium successfully located the Right button.


How the To Right Of Relative Locator Works

         Python Script
                │
                ▼
         Locate Reference Element
                │
                ▼
              Left Button
                │
                ▼
        Apply to_right_of()
                │
                ▼
      Search Elements to the Right
                │
                ▼
         Locate Right Button
                │
                ▼
           Perform Validation

Practical Example

Suppose you’re automating a payment form.

The Submit button appears to the right of the Cancel button, but neither button contains stable HTML attributes across different environments.

Instead of creating complex XPath expressions, Selenium can locate the Cancel button first and then use the to_right_of() Relative Locator to identify the Submit button reliably.

This significantly improves locator readability and maintainability.


Automation Testing Example

Consider an online banking application.

The webpage displays multiple action buttons positioned horizontally. During future UI enhancements, developers may modify HTML attributes while preserving the visual layout.

Selenium uses Relative Locators to identify elements based upon their positions, reducing automation failures during regression testing across environments.


Real-World Example

Automation engineers frequently use the to_right_of() Relative Locator while working with:

  • Banking applications.

  • E-Commerce websites.

  • Healthcare portals.

  • CRM systems.

  • ERP applications.

  • SaaS products.

  • Enterprise web applications.

  • Payment forms.

  • Dynamic dashboards.

Relative Locators are particularly useful whenever elements maintain stable visual relationships but contain changing HTML attributes.


Advantages of the To Right Of Relative Locator

  • Improves locator readability.

  • Reduces dependency on complex XPath expressions.

  • Supports dynamic webpage layouts.

  • Improves framework maintainability.

  • Produces clean and reusable automation scripts.

  • Widely used in Selenium 4 automation frameworks.


Limitations of the To Right Of Relative Locator

  • Depends upon the visual positioning of elements.

  • UI layout changes may affect locator reliability.

  • Multiple matching elements may require additional filtering.

  • Not suitable for every webpage design.


Common Mistakes Beginners Make

Using Incorrect Reference Elements

Incorrect

right_button = driver.find_element(
    locate_with(
        By.ID,
        "right-button"
    ).to_right_of(login_button)
)

Correct

right_button = driver.find_element(
    locate_with(
        By.ID,
        "right-button"
    ).to_right_of(left_button)
)

Always use the most appropriate reference element.

Ignoring Page Layout Changes

Relative Locators depend upon the visual positioning of elements. Significant UI changes may require locator updates.

Using Relative Locators Unnecessarily

If a stable ID or Name attribute uniquely identifies an element, prefer simpler locator strategies whenever appropriate.


Best Practices

  • Use stable reference elements whenever possible.

  • Prefer Relative Locators when visual relationships improve locator reliability.

  • Verify webpage layouts using browser Developer Tools.

  • Keep automation scripts simple and readable.

  • Use Relative Locators alongside traditional locator strategies when appropriate.

  • Write maintainable and reusable locators within automation frameworks.


Conclusion

The to_right_of() Relative Locator introduced in Selenium 4 provides a powerful and readable way to locate web elements based upon their visual relationships with other elements. It significantly improves locator flexibility when working with modern web applications that contain dynamic or frequently changing HTML attributes.

Understanding the to_right_of() Relative Locator provides an excellent foundation for learning other Selenium 4 Relative Locators such as above(), below(), to_left_of(), and near().


Frequently Asked Questions (FAQs)

What is the To Right Of Relative Locator?

The to_right_of() Relative Locator identifies an element that is positioned to the right of another known element on a webpage.

What is the syntax for the To Right Of Relative Locator?

driver.find_element(
    locate_with(
        By.ID,
        "element"
    ).to_right_of(reference_element)
)

Why is the To Right Of Relative Locator useful?

It improves locator readability and allows Selenium to locate elements based upon their visual positions.

Can Relative Locators replace XPath completely?

No.

Relative Locators complement traditional locator strategies such as ID, CSS Selectors, and XPath. The most suitable locator should always be chosen based upon the application’s requirements.

When should I use the To Right Of Relative Locator?

Use it whenever elements maintain stable visual relationships but do not contain reliable or unique HTML attributes.


Key Takeaways

  • The to_right_of() Relative Locator identifies elements positioned to the right of a reference element.

  • Relative Locators improve locator readability and maintainability.

  • Use stable reference elements whenever possible.

  • Relative Locators are widely used in Selenium 4 automation frameworks.

  • Choose the simplest and most reliable locator strategy for every automation scenario.

  • The to_right_of() Relative Locator is particularly useful when automating modern and dynamic web applications.