Selenium 4 Relative Locators – above, below, near, toRightOf, toLeftOf (Complete Guide)
By Bhau Automation Lab • Selenium 4 New Locators with Practical Examples
🎯 What You Will Learn in This Video
- What are Relative Locators in Selenium 4 (Friendly Locators)
- How to use above(), below(), near(), toRightOf(), toLeftOf()
- Difference between Selenium 3 locators and Selenium 4 Relative Locators
- Find elements using position of other elements
- Practical examples of Selenium 4 Relative Locators in Java
💡 Pro Tip: Use Relative Locators when unique attributes (id, name, xpath) are not available on web elements.
📌 What are Relative Locators in Selenium 4?
Relative Locators (previously called Friendly Locators) allow you to locate web elements based on their relative position to other elements. Selenium 4 introduced these locators to make test scripts more readable and robust.
📍 Types of Relative Locators in Selenium 4
- above() – Finds element above another element
- below() – Finds element below another element
- near() – Finds element near another element
- toRightOf() – Finds element to the right of another element
- toLeftOf() – Finds element to the left of another element
💻 Selenium 4 Relative Locators Example (Java)
import static org.openqa.selenium.support.locators.RelativeLocator.with;
WebElement password = driver.findElement(By.id("password"));
WebElement username = driver.findElement(with(By.tagName("input")).above(password));
WebElement loginBtn = driver.findElement(with(By.tagName("button")).below(password));
WebElement rememberMe = driver.findElement(with(By.tagName("input")).toLeftOf(loginBtn));
WebElement helpLink = driver.findElement(with(By.tagName("a")).near(loginBtn));
🔄 Difference: Selenium 3 Locators vs Selenium 4 Relative Locators
| Selenium 3 | Selenium 4 |
|---|---|
| Traditional locators (id, xpath, css) | Relative Locators added |
| More complex XPath | Readable and maintainable locators |
📚 Prerequisites
- Java Programming Basics
- Java JDK Installation
- Eclipse IDE Setup
- Selenium 4 Maven Setup
- Understanding Selenium WebDriver
❓ Common Interview Questions
Q: What are Relative Locators in Selenium 4?
A: Relative Locators find elements based on their position relative to other elements.
Q: How many Relative Locators are there in Selenium 4?
A: There are 5: above, below, near, toRightOf, toLeftOf.
🎥 Watch the Complete Video Tutorial
👉 Watch on YouTube: Selenium 4 Relative Locators Tutorial
🎓 Key Takeaways
- Selenium 4 introduced Relative Locators for easy element identification
- above, below, near, toRightOf, toLeftOf improve locator readability
- Reduces dependency on complex XPath
- Improves test stability and maintainability
🚀 Created with ❤️ by Bhau Automation Lab