We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Find elements based on their visual position using Selenium 4's friendly locators.
Relative Locators (introduced in Selenium 4) let you find elements based on their visual position instead of just attributes. They answer questions like:
This is especially helpful when:
To use them, we import:
Then we can call with(By.tagName("...")) and chain a direction:
.above(referenceElement) - Finds an element visually above the reference.below(referenceElement) - Finds an element visually below the reference.toLeftOf(referenceElement) - Finds an element to the left of the reference.toRightOf(referenceElement) - Finds an element to the right of the reference.near(referenceElement) - Finds elements within ~50px (default) of the referencePractice using relative locators to find and interact with the surrounding boxes based on the center Reference box.
123456789101112131415161718WebElement referenceBox = driver.findElement(By.id("box-center"));
WebElement aboveBox = driver.findElement(with(By.tagName("div")).above(referenceBox));
System.out.println("Above: " + aboveBox.getText());
WebElement belowBox = driver.findElement(with(By.tagName("div")).below(referenceBox));
System.out.println("Below: " + belowBox.getText());
WebElement leftBox = driver.findElement(with(By.tagName("div")).toLeftOf(referenceBox));
System.out.println("Left: " + leftBox.getText());
WebElement rightBox = driver.findElement(with(By.tagName("div")).toRightOf(referenceBox));
System.out.println("Right: " + rightBox.getText());
WebElement nearBox = driver.findElement(with(By.tagName("div")).near(referenceBox));
System.out.println("Near: " + nearBox.getText());
driver.quit();id="box-center". This is our anchor element for all relative locators.<div> that is visually above the reference box.<div> that appears below the reference element in the rendered layout.<div> that is to the left of the reference box.<div> that is to the right of the reference box.<div> that is near the reference box (within about 50px). This will typically return the closest surrounding element."Above", "Below", "Left", "Right", "Reference"), which helps verify you found the correct element.Always use a reliable locator (id, cssSelector, or simple XPath) to find the anchor, then apply relative locators.
with(By.tagName("input")).toRightOf(labelElement) is much safer than searching any element to the right.
Relative locators shine when the visual structure is stable but attributes like IDs or classes change across builds or environments.