QA AND TEST AUTOMATION · PART 5 · UI WEB AUTOMATION · BASICS · 48 OF 112

Locators in Test Automation: Role, CSS and XPath

How UI tests find elements: the DOM, accessible roles and names, test ids, CSS selectors and XPath, with a priority order that keeps tests stable. Every locator was run on ShopRung's real page, including a surprise: a button that says "Add to cart" is named "Add Green Build Mug to cart", so a role locator by its visible text finds nothing.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • DOM and accessibility tree
  • role, label, text, test id, CSS, XPath
  • priority order
  • one match each

Notes

The DOM

The browser reads the HTML and builds the DOM, the document object model: a tree of elements, each with a tag, attributes and text. Here is one real ShopRung product card: an article with a test id and a sku attribute, a heading with a link, a price, and an add to cart button. ShopRung builds these cards with JavaScript after the page loads, which is normal today, so the DOM keeps changing while you test.

A ShopRung product card
<article class="card"
   data-testid="product-card"
   data-sku="MG-201">
  <h2><a href="#/product/4">
    Green Build Mug</a></h2>
  <span class="price">$15.00
  </span>
  <button aria-label=
   "Add Green Build Mug to cart">
    Add to cart</button>
</article>

Roles and names

The browser also builds an accessibility tree, which is what screen readers use. Each element has a role, like heading, link or button, and an accessible name. Usually the name is the visible text, but an aria label overrides it. So ShopRung's button shows add to cart, but its accessible name is add green build mug to cart. That gives screen reader users more context, though an accessibility checker flags it, as the accessibility episode shows. It also matters for tests, as you will see.

Accessibility tree
  • article heading "Green Build Mug" link "Green Build Mug" text "$15.00" button "Add Green Build Mug to cart"
  • name comes from: aria-label, then <label>, then text
  • visible text ≠ accessible name

The options

There are five families of locators. Role and name: find the button named something, the way a user would. Label, placeholder or text: find the input labelled email. Test id: an attribute added for tests, like cart count. CSS selectors: tags, classes and attributes, like the element whose sku is M G two oh one. And XPath: a path language that can walk the tree, like the article containing a link with this text.

Locator kinds
role + name
  getByRole("button", {name: ...})
label / placeholder / text
  getByLabel("Email")
test id
  getByTestId("cart-count")
CSS selector
  [data-sku="MG-201"]
XPath
  //article[.//a[text()='...']]

A real surprise

We ran these on ShopRung. Get by role, button, named add to cart: zero matches. The visible text says add to cart, but the accessible name is longer. Get by role with the full name, add green build mug to cart: exactly one. Get by text, add to cart: all twelve buttons. The role locator is precise, and it tests what assistive technology actually sees, so a change to the button's name breaks the test instead of passing silently.

Run on ShopRung (counts)
getByRole("button",
  {name: "Add to cart"})     → 0
getByRole("button", {name:
  "Add Green Build Mug to cart"})
                              → 1
getByText("Add to cart",
  {exact: true})             → 12

the role locator shows how the
  button is REALLY named

Priority order

A good order of preference. First, role and accessible name, because that is how users and assistive technology find things, and it rarely changes for no reason. Second, labels, placeholders and text. Third, a test id, when there is no good role or text, such as a counter. Fourth, CSS on stable attributes. Fifth, XPath, only when you need to walk the tree. Never generated class names, long paths, or positions.

Choose in this order
  • 1 role + accessible name
  • 2 label, placeholder, text
  • 3 test id (data-testid)
  • 4 CSS on stable attributes
  • 5 XPath, only when needed
  • never: generated classes (.css-1x2y3z), long paths, nth-child chains, positions

Brittle vs stable

Here are two locators that both find the green mug's button today. The brittle one is a CSS path: main, then the grid div, then the fourth article, then its button. Sort the products differently, add one, or wrap the grid in another div, and it silently finds the wrong product or nothing. The stable one says: the product card that contains green build mug, then its button. It survives layout changes because it describes meaning, not position.

Same mug, two locators
brittle:
 main > div.grid >
   article:nth-child(4) button
 breaks when: order, layout or
   markup changes

stable:
 getByTestId("product-card")
  .filter({hasText: "Green ..."})
  .getByRole("button")

CSS and XPath

CSS and XPath are still worth knowing, especially with Selenium, which has no built in role locators. CSS: hash for an id, dot for a class, square brackets for attributes, greater than for a direct child, and starts with matching. XPath: attribute tests with at, exact text, an article that has a matching link inside, going up to a parent with two dots, and contains. XPath can go upwards; CSS mostly cannot.

Useful syntax
CSS
  #q  .price  [data-sku="MG-201"]
  article > h2   a[href^="#/p"]
XPath
  //button[@type='submit']
  //a[text()='Green Build Mug']
  //article[.//a[...]]  (has)
  //td[.='PAID']/..   (parent)
  contains(@class, "out")

Strict matching

A locator that matches several elements is a bug waiting to happen. Playwright is strict: if an action's locator matches two or more elements, it fails with an error listing them, instead of clicking a random one. Selenium's find element quietly takes the first match. Either way, narrow the locator: scope it inside a parent, filter by text, or use the exact name, until it means exactly one thing.

One match, or a clear error
  • Playwright: actions are strict 2+ matches → error, not a random click
  • Selenium findElement: takes the FIRST match silently
  • narrow down: scope inside a parent .filter({ hasText }) exact names

Common mistakes

Locator mistakes. Pasting the browser's copy XPath, an absolute path from the root that breaks on any change. Generated class names from CSS frameworks. Index and nth child chains. Text that changes by language or experiment, used without thought. One test id reused for different things. And the same locator copied into many tests, so one UI change means editing dozens of files; page objects, later in this part, fix that.

Avoid these
  • copying the browser's "Copy XPath" (/html/body/...)
  • auto-generated class names
  • nth-child and index chains
  • text that changes by locale or A/B test, used blindly
  • one test id for many things
  • locators repeated in tests

Say it like this

In the interview: I prefer role and accessible name, as users and screen readers see the page, then labels and text, then data test ids, then CSS on stable attributes, and XPath last. I avoid absolute paths, generated classes and indexes. Each locator should match exactly one element, so I scope inside parents and filter by text, and I keep locators in page objects or helpers, not scattered across tests.

In the interview
  • "I prefer role and accessible
  • name, then labels and text, then data-testid, then CSS on stable attributes, and XPath
  • last. I avoid absolute paths, generated classes and indexes, make each locator match one element, scope inside parents, and keep them in page objects."

Interview questions

Q1What is the DOM?

The Document Object Model: the browser's live tree of elements built from HTML and changed by JavaScript; UI tests locate elements in it.

Q2Which locator strategy is most stable?

Usually role plus accessible name, then labels/text, then dedicated test ids; avoid positional CSS/XPath and generated class names.

Q3What is an accessible name?

The name assistive technology announces for an element, from aria-label/aria-labelledby, an associated label, or its text content.

Q4CSS selector or XPath?

CSS is shorter and fast for attributes and classes; XPath can match text and walk up to parents or ancestors. Prefer neither when a role or test id works.

Q5What is data-testid?

An attribute added for tests that stays stable when text or styling changes; used when no good role or label exists.

Q6What happens in Playwright if a locator matches several elements?

Actions are strict and fail with an error listing the matches; narrow the locator with scoping, filter or exact names.

Q7Why is an absolute XPath bad?

It encodes the full position from the root, so any layout change breaks it or makes it point to a different element.

Q8Write an XPath that selects the row containing the text PAID.

//tr[td[.='PAID']], or //td[.='PAID']/.. to step up from the cell to its parent row.