Selenium 4 Relative Locator Examples

A few Selenium 4 relative locator examples in Ruby language

Zhimin Zhan
5 min readNov 11, 2021

--

This article is included in my “How to in Selenium WebDriver” series.

Relative locators, introduced in Selenium 4, provide a new way to find element(s) based on the position of another element. There are five locators:

  • left
  • right
  • above
  • below
  • near

In this article, I will show some examples using relative locators in Selenium 4.

Table of Contents:· Get the element on the right of a checkbox
· Get the element(s) on the left of a checkbox
· Near
· Above (in a table)
· Below (in a table)
· Summary

Get the element on the right of a checkbox

HTML:

<p><input type="checkbox" id="test_products_only_flag">
<span>Test automation products only</span></p>

Script with Relative (Right):

start_cell = driver.find_element(id: "test_products_only_flag")
elem_label = driver.find_element(relative: { tag_name: "span", right: start_cell })
expect(elem_label.text).to eq("Test automation products only")

XPath alternative

driver.find_element(xpath: "//input[@id='test_products_only_flag']/following-sibling::*")

Get the element(s) on the left of a checkbox

HTML:

<p><span>I accept Terms and Conditions</span>
<input type="checkbox" id="accept_terms" style="margin-bottom: 6px;"></p>

Script with Relative (Left):

start_cell = driver.find_element(id: "accept_terms")
elem_label = driver.find_element(relative: { tag_name: "span", left: start_cell })
expect(elem_label.text).to eq("I accept Terms and Conditions")

Find multiple

--

--

Zhimin Zhan

Test automation & CT coach, author, speaker and award-winning software developer. Help teams succeed with Agile/DevOps by implementing real Continuous Testing.