Playwright + TS · Lesson 17 of 36
Module 17: Locators (Deep Dive)
Try it yourself
Implement buildRowDeleteLocator:
The editor has a worked example. Read it, tweak it, then press Mark as complete.
Playwright recommends prioritizing locators in this order:
<label> elements.data-testid).Playwright enforces strict mode on all locators by default! If your locator matches more than one element, Playwright will throw an error:
// ❌ If there are 3 buttons matching "Delete", this throws StrictModeError:
await page.getByRole("button", { name: "Delete" }).click();
// ✅ Solution 1: Filter to pinpoint specific row
await page.locator("tr", { hasText: "Order #402" })
.getByRole("button", { name: "Delete" })
.click();
// ✅ Solution 2: Filter by child locator
await page.getByRole("listitem")
.filter({ has: page.getByRole("heading", { name: "MacBook Pro" }) })
.getByRole("button", { name: "Buy" })
.click();
// ✅ Solution 3: Exact index (first / last / nth)
await page.getByRole("button", { name: "Delete" }).first().click();Locators can be chained seamlessly:
const nav = page.getByRole("navigation");
const loginLink = nav.getByRole("link", { name: "Sign in" });
await loginLink.click();Locators are the foundation of reliable test automation. Playwright prioritizes user-facing, accessible locators like getByRole and getByLabel over fragile CSS or XPath selectors. In this deep dive, you will learn how to locate elements the way real users see them, handle strict mode violations, and filter dynamic lists with zero flakiness. Let's master locators!
Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.
getByRole ensures your app remains accessible to users with screen readers and disability tools. If an engineer forgets a label or uses a div instead of a button, getByRole fails, catching accessibility bugs automatically.
page.$ is legacy Puppeteer-style; it queries the DOM at a single instant without auto-waiting. page.locator returns a resilient locator that evaluates actionability dynamically whenever an action is called.
Finished reading?
Review the worked example in the editor, then mark the lesson complete.