By Shivam Singh, founder of TesterRank · Updated September 2026
Every time you need to find an element, follow this checklist from top to bottom. Stop at the first one that works.
Modern apps add data-testid attributes specifically for automation. They're the gold standard because: (1) they exist only for testing — devs don't touch them during UI changes, (2) they're never auto-generated or dynamic, (3) they survive CSS refactors. Both the Banking and Shopping portals use data-testid extensively.
// data-testid — access via CSS selector
WebElement loginBtn = driver.findElement(
By.cssSelector("[data-testid='loginBtn']"));
WebElement searchBox = driver.findElement(
By.cssSelector("[data-testid='search-box']"));
WebElement productName = driver.findElement(
By.cssSelector("[data-testid='product-name-1']"));
// Same thing with XPath (slightly slower)
WebElement loginBtnXPath = driver.findElement(
By.xpath("//*[@data-testid='loginBtn']"));If you have any influence on the app, ask developers to add data-testid to key elements. Most frontend devs understand this — React, Angular, and Vue communities all recommend it. It's not extra work for them, and it saves you hours.
Each step in the checklist is more likely to break than the one above it. A data-testid exists only for testing, so developers rarely change it. An id is usually stable but sometimes generated. Class names change whenever the design changes. Long XPath expressions break when anyone moves a single div. Picking the highest stable option saves you hours of fixing tests later.
| Locator | How stable | Typical reason it breaks |
|---|---|---|
| data-testid | Very high | Almost never; it exists for tests |
| id | High | Framework generates ids like "input-4821" |
| name | High | Form field renamed |
| CSS class | Medium–low | Design or CSS framework update |
| Text (XPath) | Medium | Wording or language change |
| Absolute XPath | Very low | Any change in page structure |
If an element has no good locator, ask the developer to add a data-testid. It takes them one minute and saves the team many broken builds. Good testers ask for testability; they do not just work around it.
Key Point: Priority: id → data-testid → name → CSS selector → XPath. Always start from the top.