🎯 Locators — Element Finding Strategies

Locators — Element Finding Strategies: Choosing a locator directly mirrors choosing a collection access strategy in Java: By.id is a Map key lookup — O(1), the browser calls getE

Choosing a locator directly mirrors choosing a collection access strategy in Java: By.id is a Map key lookup — O(1), the browser calls getElementById internally. By.xpath, by contrast, works like scanning an unsorted List — it may traverse the entire DOM tree. So if pages seem to always have IDs, why do you ever need XPath or CSS selectors? Because front-end frameworks (React, Angular) can regenerate the DOM on each render, making IDs unstable or absent; in those cases structural queries like `//button[normalize-space()='Buy']` become the only reliable anchor. In Java you wrote By.id("loginBtn"); in Python it is By.ID, in TypeScript the same — only syntax differs, the locator strategy stays constant. The most dangerous locator for QA is By.className("btn"): when a designer refactors CSS class names, the locator silently starts matching different elements, the test returns a false PASS, and no exception is thrown — the hardest category of flaky test to diagnose.

🎬 The Most Dangerous Locator: The Silent Trap of By.className

"Buy Now" (class="btn")

Designer refactors the CSS

"Cancel" (class="btn")

Wrong button clicked

`By.className("btn")` — finds the "Buy Now" button, clicks it, the test PASSES. Everything looks perfect.

The test stayed green, nobody suspected anything — but `By.className` ALWAYS returns the first matching element, even if no other element shares that class YET.

Weeks later: a designer adds `class="btn"` to the "Cancel" button too, for style consistency — the page looks unchanged, but now TWO elements share that class.

`By.className("btn")` may now find the "Cancel" button instead, depending on DOM order — which one comes first is determined by HTML order, not CSS.

The test runs the SAME code, clicks the SAME way — but now it clicks "Cancel" instead of "Buy Now". There is NO exception, because the element genuinely existed and was genuinely clickable.

The test report says: "PASSED". But the checkout flow was never actually tested — an order was cancelled and nobody noticed. This is the hardest kind of flaky test to find: one that errors nowhere, but silently does the WRONG thing.

Final — the Java bridge: `By.className` is like an `instanceof` check that matches by NAME, not by unique identity; if multiple classes share a name, you catch the wrong object. The safe choice: `By.id` or `data-testid` — an identity design will NEVER touch.

Locator Types — Quick Comparison