Relative Locators (Selenium 4)
Relative locators find an element by describing where it is compared to another element, as a person would: "the input below the Email label".
| Method | Meaning |
|---|---|
.above(el) | Element is above el |
.below(el) | Element is below el |
.to_left_of(el) | Element is to the left |
.to_right_of(el) | Element is to the right |
.near(el) | Within about 50 pixels. You can pass a distance |
Choosing a Locator Strategy
A test that fails because a locator changed is a maintenance cost. Choose locators that survive redesigns.
| Rank | Locator | Stability |
|---|---|---|
| 1 | data-testid / data-test / data-qa attributes | Excellent: added just for tests |
| 2 | id (not auto-generated) | Very good |
| 3 | name, aria-label, placeholder | Good |
| 4 | Short CSS using meaningful classes | Good |
| 5 | XPath with text or a stable neighbor | Medium |
| 6 | Relative locators | Medium (layout dependent) |
| 7 | Absolute XPath, long chains, indexes like div[3]/div[2] | Poor. Avoid |
Practice Site Example
The practice shop saucedemo.com adds data-test attributes:
Keep Locators in One Place
The * unpacks the tuple into the two arguments. When the page changes you fix one line. This idea becomes the Page Object Model later.
Checklist Before You Choose
- Is it unique? (1 match in DevTools)
- Is it stable? (not a number or random string)
- Is it readable? (another tester understands it)
- Is it independent of layout? (no long paths)
- Could a developer add a
data-testidto make it perfect?
Conclusion
Relative locators describe position, but stable attributes are always better. Prefer data-testid, then id and name, then short CSS or XPath, and store locators in one place.

