We mentioned the features that you can expect from Selenium 4 in our previous post. In this post we are going in more details on one new feature – Relative Locators.
With Selenium 3.0, each element is accessed separately as there is no way to access a web element relative to the nearby elements.
Selenium 4 will bring out a new Locator that has been in plans for quite some time now called Relative Locator. This new locator enables you to find the nearby elements based on their visual location relative to other elements in the DOM.
We are going to do a deep dive into how you can use the latest Selenium 4 Relative Locator for your daily automation testing.
What are Relative Locators
Selenium 4 brings Relative Locators (originally named Friendly Locators). This functionality was added to help you locate elements that are nearby other elements.
The available options are:
- above(): Web element to be searched/located appears above the specified element.
- below(): Web element to be searched/located appears below the specified element.
- toLeftOf(): Web element to be searched/located appears to the left of the specified element.
- toRightOf(): Web element to be searched/located appears to the right of the specified element.
- near(): Web element is at most 50 pixels away from specified element. There’s also an overloaded method to allow you to specify the distance.
All these methods are overloaded to accept a By or a WebElement object.
How to use Relative Locators
Given a blog application, we may want to verify that the blog to the left of “Pros and Cons of Katalon Studio” is “Appium Automation Top 8 Mistakes”. Now relative locators allow us to do this.
Here is the DOM snippet for the blogs.
“Pros and Cons of Katalon Studio” is represented in the DOM by id recent-2, and “Appium Automation Top 8 Mistakes” is recent-1.
The WebDriver – findElement method can accept the withTagName() method which returns a RelativeLocator.RelativeBy object (a descendant of By).
From here, I can specify relative locators. I know that “Appium Automation Top 8 Mistakes” (recent-1) is to the left of “Pros and Cons of Katalon Studio” (recent-2). So, I can specify both of these:
This returns Appium Automation Top 8 Mistakes” (recent-1).
Write your test scripts with relative locators.
How does it work?
Selenium 4 uses the JavaScript function getBoundingClientRect() to find the relative elements. This function returns properties of an element such as right, left, bottom, and top.
Here is a screenshot of the implementation that highlights the usage of relative locators in Selenium automation testing.
What’s your opinion on the new locator?
Relative locator in Selenium 4 is an interesting advancement using which developers can access nearby web elements with fewer lines of implementation.
As this is an alpha version of Selenium WebDriver, the implementation could change in further releases.
Do let me know your opinion on the new locator?