Relative Locators

Loading concept...

🎯 Selenium Relative Locators: Finding Elements Like a Pro!

The Treasure Hunt Analogy 🗺️

Imagine you’re on a treasure hunt in a big room full of toys. Someone tells you: “Find the red ball that’s next to the teddy bear.”

You don’t need the ball’s exact address. You just need to know where the teddy bear is, and then look beside it!

That’s exactly how Relative Locators work in Selenium!

Instead of finding an element by its exact ID or class, you find it by describing where it is compared to another element you already know.


🤔 Why Do We Need Relative Locators?

Sometimes, web pages are tricky:

  • Elements don’t have unique IDs
  • Class names are confusing or shared by many elements
  • The page changes, and your old locators break

Relative Locators save the day! They help you say:

“I want the button that’s below this label”

Just like giving directions to a friend!


🎨 The Five Magic Words (Relative Locator Types)

Relative Locators use five special directions. Think of them like compass directions, but for web pages:

graph TD A[🎯 Reference Element] --> B[⬆️ ABOVE] A --> C[⬇️ BELOW] A --> D[⬅️ TO LEFT OF] A --> E[➡️ TO RIGHT OF] A --> F[📍 NEAR]

1️⃣ above() - Look Up! ⬆️

Find an element that sits above another element.

Real Life Example:

“Find the title that’s above the description paragraph”

# Python Example
from selenium.webdriver.support.relative_locator import locate_with
from selenium.webdriver.common.by import By

# First, find the reference element
description = driver.find_element(By.ID, "description")

# Now find what's ABOVE it
title = driver.find_element(
    locate_with(By.TAG_NAME, "h1").above(description)
)
// Java Example
WebElement description = driver.findElement(By.id("description"));
WebElement title = driver.findElement(
    with(By.tagName("h1")).above(description)
);

2️⃣ below() - Look Down! ⬇️

Find an element that sits below another element.

Real Life Example:

“Find the Submit button that’s below the password field”

# Python Example
password_field = driver.find_element(By.ID, "password")

submit_btn = driver.find_element(
    locate_with(By.TAG_NAME, "button").below(password_field)
)
// Java Example
WebElement passwordField = driver.findElement(By.id("password"));
WebElement submitBtn = driver.findElement(
    with(By.tagName("button")).below(passwordField)
);

3️⃣ toLeftOf() - Look Left! ⬅️

Find an element that’s to the left of another element.

Real Life Example:

“Find the label that’s to the left of the input box”

# Python Example
input_box = driver.find_element(By.ID, "email-input")

label = driver.find_element(
    locate_with(By.TAG_NAME, "label").to_left_of(input_box)
)
// Java Example
WebElement inputBox = driver.findElement(By.id("email-input"));
WebElement label = driver.findElement(
    with(By.tagName("label")).toLeftOf(inputBox)
);

4️⃣ toRightOf() - Look Right! ➡️

Find an element that’s to the right of another element.

Real Life Example:

“Find the Edit button that’s to the right of the username”

# Python Example
username = driver.find_element(By.ID, "username")

edit_btn = driver.find_element(
    locate_with(By.TAG_NAME, "button").to_right_of(username)
)
// Java Example
WebElement username = driver.findElement(By.id("username"));
WebElement editBtn = driver.findElement(
    with(By.tagName("button")).toRightOf(username)
);

5️⃣ near() - Look Nearby! 📍

Find an element that’s close to another element (within ~50 pixels by default).

Real Life Example:

“Find the help icon that’s near the form field”

# Python Example
form_field = driver.find_element(By.ID, "phone")

help_icon = driver.find_element(
    locate_with(By.CLASS_NAME, "help-icon").near(form_field)
)

# You can also set a custom distance!
help_icon = driver.find_element(
    locate_with(By.CLASS_NAME, "help-icon").near(form_field, 100)
)
// Java Example
WebElement formField = driver.findElement(By.id("phone"));
WebElement helpIcon = driver.findElement(
    with(By.className("help-icon")).near(formField)
);

// With custom distance (100 pixels)
WebElement helpIcon = driver.findElement(
    with(By.className("help-icon")).near(formField, 100)
);

🔗 Chaining Relative Locators - Super Powers Combined!

Here’s where the magic gets really powerful! 🚀

You can combine multiple directions to pinpoint exactly what you want. It’s like giving super-specific directions:

“Find the button that’s below the header AND to the right of the cancel button”

graph TD H[🏷️ Header] --> |below| TARGET C[❌ Cancel Button] --> |to right of| TARGET TARGET[🎯 TARGET: Submit Button]

Example: Chaining Two Locators

# Python Example - Chain two directions!
header = driver.find_element(By.ID, "form-header")
cancel_btn = driver.find_element(By.ID, "cancel")

submit_btn = driver.find_element(
    locate_with(By.TAG_NAME, "button")
    .below(header)
    .to_right_of(cancel_btn)
)
// Java Example - Chain two directions!
WebElement header = driver.findElement(By.id("form-header"));
WebElement cancelBtn = driver.findElement(By.id("cancel"));

WebElement submitBtn = driver.findElement(
    with(By.tagName("button"))
    .below(header)
    .toRightOf(cancelBtn)
);

Example: Chaining Three Locators!

When you need to be even more specific:

# Python - Triple chain!
reference1 = driver.find_element(By.ID, "ref1")
reference2 = driver.find_element(By.ID, "ref2")
reference3 = driver.find_element(By.ID, "ref3")

target = driver.find_element(
    locate_with(By.CLASS_NAME, "target-class")
    .below(reference1)
    .to_right_of(reference2)
    .near(reference3)
)
// Java - Triple chain!
WebElement ref1 = driver.findElement(By.id("ref1"));
WebElement ref2 = driver.findElement(By.id("ref2"));
WebElement ref3 = driver.findElement(By.id("ref3"));

WebElement target = driver.findElement(
    with(By.className("target-class"))
    .below(ref1)
    .toRightOf(ref2)
    .near(ref3)
);

🧠 How Does Selenium Calculate Positions?

Behind the scenes, Selenium uses JavaScript to find the exact position of elements on the screen. It looks at:

  1. Bounding Box - The rectangle around each element
  2. Center Point - The middle of that rectangle
  3. Distance - How far apart the centers are
graph LR A[Element A<br/>Center: 100,200] --> |Compare| B[Element B<br/>Center: 100,300] B --> C{Is B below A?} C --> |Yes! 300 > 200| D[✅ Match!]

💡 Pro Tips for Relative Locators

✅ DO:

  • Use them when traditional locators fail
  • Combine with basic locators (ID, class, tag)
  • Chain for precision
  • Use near() for loosely positioned elements

❌ DON’T:

  • Overuse when simple locators work fine
  • Forget that positions can change on different screens
  • Use on hidden or off-screen elements

🎮 Real-World Scenario

Imagine a login form:

┌─────────────────────────┐
│      LOGIN FORM         │  ← Header
├─────────────────────────┤
│ Username: [_________]   │
│ Password: [_________]   │
│                         │
│  [Cancel]  [Submit]     │
└─────────────────────────┘

Finding Submit using chains:

header = driver.find_element(By.ID, "login-header")
cancel = driver.find_element(By.ID, "cancel-btn")

submit = driver.find_element(
    locate_with(By.TAG_NAME, "button")
    .below(header)
    .to_right_of(cancel)
)

🎉 You Did It!

Now you know how to:

  • ⬆️ Find elements above others
  • ⬇️ Find elements below others
  • ⬅️ Find elements to the left of others
  • ➡️ Find elements to the right of others
  • 📍 Find elements near others
  • 🔗 Chain multiple directions for laser-precision!

Relative Locators are like giving directions to a friend. Once you learn them, finding elements becomes fun and easy! 🚀

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.