We hope you had a fabulous Diwali. So let’s discuss Relative Locators here.

Relative Locators in Selenium formerly known as Friendly Locators. You can learn about Selenium locators here. The point to be noted here is sometimes we may not find elements using these locators and to overcome that we use JavaScriptExecutor. In Selenium, relative locators are a set of locators introduced in Selenium 4 to simplify the process of locating elements on a web page, especially in dynamic and responsive user interfaces. These locators are designed to make it easier to identify elements based on their spatial relationships with other elements on the page.

There are five main relative locators in Selenium, and they are:

1. near:
– Finds an element that is located near another element.
– Example: driver.findElement(withTagName(“label”).near(By.tagName(“input”)));

2. above:
– Finds an element that is located above another element.
– Example: driver.findElement(withTagName(“label”).above(By.tagName(“input”)));

3. below:
– Finds an element that is located below another element.
– Example: driver.findElement(withTagName(“input”).below(By.tagName(“label”)));

4. toLeftOf:
– Finds an element that is located to the left of another element.
– Example: driver.findElement(withTagName(“span”).toLeftOf(By.tagName(“input”)));

5. toRightOf:
– Finds an element that is located to the right of another element.
– Example: driver.findElement(withTagName(“input”).toRightOf(By.tagName(“span”)));

Unfortunately, you cannot use these locators with @FindBy annotation of Page Object Model as of now. But if you are designing POM without using @FindBy and PageFactory, then you can surely use these locators in POM. I hope we can see these locators in upcoming versions of Selenium. What is your thought on this? Please comment below