Selenium 4 Alpha comes with a new feature which is called “Relative Locators” before it is called “Friendly Locators“. We generally write tests by using CSS and XPath locators and also of course selenium find by methods such as find by id, name, link text, etc. We also covered these functionalities in the below articles.
Selenium Xpath: https://www.swtestacademy.com/xpath-selenium/
Selenium CSS: https://www.swtestacademy.com/css-selenium/
Selenium FindBy: https://www.swtestacademy.com/selenium-find-element/
In this article, we will introduce you to a new feature that comes with Selenium 4 Alpha. By using this new feature we will easily locate elements that are close to other ones. You can also find comprehensive information about the relative locators on the Angie Jones’s blog.
We have several methods to find a close-by (relative) element. These are:
- toLeftOf(): Element located to the left of specified element.
- toRightOf(): Element located to the right of the specified element.
- above(): Element located above with respect to the specified element.
- below(): Element located below with respect to the specified element.
- near(): Element is at most 50 pixels far away from the specified element. The pixel value can be modified.
The methods which are represented above are overloaded accept a By or a WebElement.
Let’s do a quick example of this new feature. The scenario is, we will find the first article then, we will use toRightOf() and below() functions to print out and highlight right and below articles to the first article. This feature is still in the development phase (Alpha version) and it is not working sometimes as expected but we will be ready how to use this new locator strategy and when it will be stable, our codes will be ready for this. :)
In the below code snippet, you can find the details. I commented above() and toLeftOf() functions because for the first article there are no left and above articles.
Onur Baskirt is a senior IT professional with 15+ years of experience. Now, he is working as a Senior Technical Consultant at Emirates Airlines in Dubai.