Relative Locators in Selenium
By Sonal Dwivedi, Community Contributor - September 27, 2023
Selenium 3 has 8 locators namely ID, Name, class, XPath, CssSelectors, LinkText, PartialLinkText, and TagName which helps us to locate the web elements on DOM. Relative locators are a new advancement that was introduced in Selenium 4 which was previously called friendly locators.
They are convenient to use when it is challenging to create a locator for the desired element, but easy to describe structurally where the element is in relation to an element that can be easily located. In simple words, relative locators allow us to locate the web elements based on their relative position with respect to other web elements.
Selenium 4 uses the JavaScript function getBoundingClientRect() to determine the size and position of web elements on the page, and can use this information to locate neighbouring elements.
Read More: Locators in Selenium: A Detailed Guide
Relative Locators in Selenium 4
Selenium 4 introduced Relative Locators. These 5 relative locators in Selenium 4 are:
- above()
- below()
- toLeftOf()
- toRightOf()
- near()
1. above()
above() is used to locate the web element(s) just above the specified element.
Syntax:
To locate element(s) that is above a specific locator:
above(By locator)
To locate element(s) that is above a specific web element:
above(WebElement element)
2. below()
below() is used to locate the web element(s) just below the specified element.
Syntax:
To locate element that is below a specific locator:
below(By locator)
To locate element that is below a specific web element:
below(WebElement element)
3. toLeftOf()
It is used to locate the web element(s) present on the left of the specified element.
Syntax:
To locate element that is to the left a specific locator:
toLeftOf(By locator)
To locate element that is to the left a specific web element:
toLeftOf(WebElement element)
4. toRightOf()
It is used to locate the web element(s) present on the right of the specified element.
Syntax:
To locate element that is to the right a specific locator:
toRightOf(By locator)
To locate element that is to the right a specific web element:
toRightOf(WebElement element)
5. near()
It is used to locate the web element(s) located at approximately 50 pixels away from the specified element. The distance can be passed as an argument to an overloaded method
Syntax:
near(By locator)
near(WebElement element)
near(By locator, int atMostDistanceInPixels)
near(WebElement element, int atMostDistanceInPixels)
How to use Relative locators in Selenium: Example
To understand all the above relative locators practically with Selenium script, let us first set up the prerequisites.
Pre-requisites:
1. Eclipse IDE or any other editor installed.
2. Create a Maven project in Eclipse and add the latest Selenium 4 Java dependency in the pom.xml file of the Maven project.
<dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.11.0</version> </dependency> </dependencies>
Relative locators were introduced in Selenium 4.0.0-alpha-3. So, make sure you have any latest dependency after 4.0.0-apha-3 in the pom.xml file.
We would be using BrowserStack’s Website to understand how relative locators work in Selenium 4.
1. above():
In the above image, “Get A Demo” button is above “App Live”. Let us assume that “Get A Demo” button element does not have any unique identifier, so in that case we can locate “App Live” element and then use above() relative locator method to access the above element that is “Get A Demo”.
Step 1 First, create a Web Element for the “App Live” element in Eclipse IDE or any editor.
WebElement appLive=driver.findElement(By.cssSelector("a.product-card-app-live"));
Step 2 Next with the help of Eclipse IDE/ any IDE, we will try to import the RelativeLocator package and understand the syntax of Relative Locator method.
Type below line of code:
driver.findElement(RelativeLocator.)
Choose RelativeLocator class which belongs to org.openqa.selenium.supports.locators. This will automatically import the said package inside your class.
import org.openqa.selenium.support.locators.RelativeLocator;
Step 3 Enter “.” after RelativeLocator, and we can see the “with” method of the Relative Locator class which takes the “By” object as a parameter.
Choose “with” method which will give you below code:
WebElement getADemo=driver.findElement(RelativeLocator.with(by));
Step 4 Now, “with” method is expecting a “By” locator of the element whose locator is not defined (Get A Demo), and as from the above image we know that “Get A Demo” consists of a button tag, we can write below code:
WebElement getADemo=driver.findElement(RelativeLocator.with(By.tagName("button")));
Step 5 Next, we need to use the relative method (above(), below(), toLeftOf(), toRightOf(), near()) along with the element whose locator is known (App Live element). For that, enter “.” after the “with” method completes.
We will be choosing “above(WebElement element)” and by adding the “App Live” locator inside the parenthesis, the code looks like below:
WebElement getADemo=driver.findElement(RelativeLocator.with(By.tagName("button")).above(appLive));
Step 6 Finally, we can use getADemo locator to perform click() operation.
getADemo.click();
Complete code for Relative Locators above() Example:
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 RLocators { public static void main(String args[]) throws InterruptedException { WebDriver driver; driver = new ChromeDriver(); driver.get("https://www.browserstack.com/"); WebElement appLive = driver.findElement(By.cssSelector("a.product-card-app-live")); WebElement getADemo = driver.findElement(RelativeLocator.with(By.tagName("button")).above(appLive)); getADemo.click(); } }
2. below()
Similarly, if we need to locate “Get A Demo” element which is below “Text Section” area, we can use “Text Section” locator and create a locator for “Get A Demo” by using below() relative method.
WebElement textSection = driver.findElement(By.cssSelector("div.text-section p"));
“Get A Demo” locator using below relative method would be:
WebElement getADemo=driver.findElement(RelativeLocator.with(By.tagName("button")).below(textSection));
Complete code for below():
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 RLocators { public static void main(String args[]) throws InterruptedException { WebDriver driver; driver = new ChromeDriver(); driver.get("https://www.browserstack.com/"); WebElement textSection = driver.findElement(By.cssSelector("div.text-section p")); WebElement getAdemo = driver.findElement(RelativeLocator.with(By.tagName("button")).below(textSection)); getAdemo.click(); } }
3. toRightOf()
If we need to click on “Get A Demo” button, which is to the right of the “Get Started Free” link, we can do that with the below code.
WebElement getStartedFree = driver.findElement(By.cssSelector("a#signupModalButton")); WebElement getADemo = driver.findElement(RelativeLocator.with(By.tagName("button")).toRightOf(getStartedFree)); getADemo.click();
4. toLeftOf()
Similarly, if we need to click on “Get Started Free” link, which is to the left of “Get A Demo” button, we can do that by below code:
WebElement getADemoo = driver.findElement(By.xpath("//button[contains(@class, 'btn-secondary') and text()='Get a demo']")); WebElement getStartedFreee = driver.findElement(RelativeLocator.with(By.tagName("a")).toLeftOf(getADemoo)); getStartedFreee.click();
5. near()
near() finds an element located near to the specified element which is approximately 50 pixels away. We can also give the distance of our choice in an overloaded method. Below code will click on the “Search” button which is near to the “Free Trial” link.
WebElement freeTrial = driver.findElement(By.xpath("//ul[@id='primary-menu']//a[@id='free-trial-link-anchor']")); WebElement search = driver.findElement(RelativeLocator.with(By.tagName("button")).near(freeTrial)); search.click();
Complete code for toRightOf() and toLeftOf() and near():
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 RLocators { public static void main(String args[]) throws InterruptedException { WebDriver driver; driver = new ChromeDriver(); driver.get("https://www.browserstack.com/"); WebElement getStartedFree = driver.findElement(By.cssSelector("a#signupModalButton")); WebElement getADemo = driver.findElement(RelativeLocator.with(By.tagName("button")).toRightOf(getStartedFree)); getADemo.click(); driver.get("https://www.browserstack.com/"); driver.manage().window().maximize(); WebElement getADemoo = driver .findElement(By.xpath("//button[contains(@class, 'btn-secondary') and text()='Get a demo']")); WebElement getStartedFreee = driver.findElement(RelativeLocator.with(By.tagName("a")).toLeftOf(getADemoo)); getStartedFreee.click(); driver.get("https://www.browserstack.com/"); WebElement freeTrial = driver .findElement(By.xpath("//ul[@id='primary-menu']//a[@id='free-trial-link-anchor']")); WebElement search = driver.findElement(RelativeLocator.with(By.tagName("button")).near(freeTrial)); search.click(); } }
Chaining Relative locators
Sometimes finding an element using only one relative locator is not sufficient. Selenium 4 supports multiple relative locators to find a fixed web element which is called chaining Relative Locators. We can combine more than one relative locators depending on the position of the searched element.
Suppose we need to click on the “Get a Demo” button which is below the “Text Section” area and to the right of the “Get started free” link. This can be achieved by combining the below() and toRightOf() method to land on the “Get a demo” button.
Complete code:
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 RLocators { public static void main(String args[]) throws InterruptedException { WebDriver driver; driver = new ChromeDriver(); driver.get("https://www.browserstack.com/"); WebElement textSection = driver.findElement(By.cssSelector("div.text-section p")); WebElement getStartedFree = driver.findElement(By.cssSelector("a#signupModalButton")); WebElement getADemo=driver.findElement(RelativeLocator.with(By.tagName("button")).below(textSection).toRightOf(getStartedFree)); getADemo.click(); } }
Advantages of Relative Locators in Selenium
- Relative locators are easy to create and implement as it uses simple and natural language such as above, toRightOf or near to any web element to locate the desired web element. This makes the script more readable and easier to understand.
- It reduces code complexity by eliminating the need for complex XPath or CSS selector combinations.
- It saves time as testers don’t need to spend as much time crafting complex locators using XPath and CSS Selectors.
- Relative Locators are beneficial for unstable applications, elements with dynamic values, and elements without unique attribute values.
Limitations of Relative Locators in Selenium
- Using relative locators requires extra caution when it comes to the size of the window on which tests are running. Resizing the window elements would not be in the same position, they may overlap which can cause the desired element to not be found. In such cases, relative locator methods i.e. above, below, toLeftOf, toRightOf, near do not work with overlapping elements.
- Using Relative Locators may introduce a slight performance overhead, as the WebDriver needs to perform additional calculations to locate elements based on their relationships with other elements.
- Relative locators depend on the visibility of the neighbouring web elements. If the neighbouring web elements are not visible, relative locators may result in incorrect behaviour or test failure.
- If the webpage structure changes significantly, the relative locators may need to be updated accordingly.
Conclusion
Relative locators add another layer of finding elements with above(), below(), toLeftOf(), toRightOf(), and near() locators. It makes locating elements easier when another element’s locator is known. However, it is always advisable to test the website on real devices under real user conditions on different screen resolutions for more accurate results.
BrowserStack real device cloud offers 3000+ real devices and browsers to test the website extensively and provide accurate results under real world conditions. You can run parallel tests using Cloud Selenium Grid where same tests can be run on different devices-browser-OS combinations to tests cross browser compatibility of the website.