0
0
Selenium-pythonHow-ToBeginner · 4 min read

How to Use Relative Locators in Selenium for Easier Element Finding

In Selenium, use RelativeLocator to find elements based on their position relative to other known elements, such as above, below, toLeftOf, toRightOf, or near. This helps when elements lack unique IDs or classes. You first locate a reference element, then use RelativeLocator.withTagName() combined with position methods to find the target element.
📐

Syntax

The basic syntax uses RelativeLocator.withTagName() to specify the tag of the element you want to find, then chain position methods like above(), below(), toLeftOf(), toRightOf(), or near() to locate it relative to a known element.

Example parts:

  • driver.findElement(RelativeLocator.withTagName("tag").below(referenceElement)) finds an element with the given tag below the reference element.
  • referenceElement is a WebElement you already found.
java
WebElement referenceElement = driver.findElement(By.id("knownElementId"));
WebElement targetElement = driver.findElement(RelativeLocator.withTagName("tagName").below(referenceElement));
💻

Example

This example shows how to find a button below a label using relative locators in Selenium with Java.

java
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 RelativeLocatorExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://www.w3schools.com/howto/howto_css_login_form.asp");

            // Find the label element by its text
            WebElement label = driver.findElement(By.xpath("//label[text()='Username']"));

            // Find the input element below the label using relative locator
            WebElement inputBelowLabel = driver.findElement(RelativeLocator.withTagName("input").below(label));

            // Enter text to verify it works
            inputBelowLabel.sendKeys("testuser");

            System.out.println("Input found and text entered successfully.");
        } finally {
            driver.quit();
        }
    }
}
Output
Input found and text entered successfully.
⚠️

Common Pitfalls

  • Not importing RelativeLocator class causes compilation errors.
  • Using relative locators without a reliable reference element leads to wrong or no matches.
  • Choosing the wrong tag name in withTagName() can cause no element found.
  • Relative locators may fail if the page layout changes or elements overlap.
  • Always ensure the reference element is visible and unique.
java
/* Wrong way: Missing import and wrong tag name */
// WebElement label = driver.findElement(By.id("labelId"));
// WebElement input = driver.findElement(RelativeLocator.withTagName("div").below(label)); // Wrong tag

/* Right way: Correct import and tag name */
import org.openqa.selenium.support.locators.RelativeLocator;
WebElement label = driver.findElement(By.id("labelId"));
WebElement input = driver.findElement(RelativeLocator.withTagName("input").below(label));
📊

Quick Reference

Use these position methods with RelativeLocator.withTagName() to find elements relative to a known element:

MethodDescription
above(WebElement element)Find element above the reference element
below(WebElement element)Find element below the reference element
toLeftOf(WebElement element)Find element to the left of the reference element
toRightOf(WebElement element)Find element to the right of the reference element
near(WebElement element)Find element near the reference element

Key Takeaways

Use RelativeLocator.withTagName() with position methods to find elements relative to known elements.
Always locate a reliable reference element first before using relative locators.
Choose the correct tag name matching the target element for accurate results.
Import org.openqa.selenium.support.locators.RelativeLocator to avoid errors.
Relative locators help when elements lack unique IDs or classes but depend on stable page layout.