top of page

Selenium 4 - Relative Locators

Selenium 4 offers a way of locating elements by using natural language terms. This article describes how to use the new Relative Locators.

This functionality brings a new way to locate elements to help you find the ones that are nearby other elements. The available locators are: 1.above



4.toRightOf near

The concept behind this method is to allow you to find elements based on how one would describe them on a page. It is more natural to say: “find the element that is below the image”, rather than “find the INPUT inside the DIV with the ‘id’ of ‘main’”. In general, you could think about them as a way to locate elements based on the visual placement on the page.

We will use the following login form to understand how Relative Locators work:


We would like to find the email address field, which is above the password field. To do that, we find the password field through its id, and then we use the above relative locator.


import static;

WebElement password = driver.findElement("password"));

WebElement email = driver.findElement(with(By.tagName("input")).above(passwordField));


Going the other way around, let's find the password field, which is below the email address field.


import static;

WebElement emailAddressField = driver.findElement("email"))

WebElement passwordField = driver.findElement(with(By.tagName("input")) .below(emailAddressField));

To the Left Of

Let’s consider the case where we want to find the element on the left side of the “Submit” button.


import static;

WebElement submitButton = driver.findElement("submit"));

WebElement cancelButton = driver.findElement(with(By.tagName("button")) .toLeftOf(submitButton));

To the Right Of

Now we'll consider the opposite case, where we want to find the element on the right side of the “Cancel” button.


import static;

WebElement cancelButton = driver.findElement("cancel"));

WebElement submitButton = driver.findElement(with(By.tagName("button")).toRightOf(cancelButton));


near is helpful when we need to find an element that is at most 50px away from the specified element. In this case, we would like to find the email address field by first finding the label of that field.


import static;

WebElement emailAddressLabel = driver.findElement("lbl-email"));

WebElement emailAddressField = driver.findElement(with(By.tagName("input")).near(emailAddressLabel));

22 views0 comments

Recent Posts

See All

Exception Handling in Selenium Webdriver

What is an exception? An exception is an error that occurs during the execution of a program. However, while running a program, programming languages generate an exception that must be handled to prev


Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page