Playwright + JS · Lesson 17 of 35

0/35 done

Module 17: Locators (Deep Dive)

17. Resilient User-First Locators & Filtering

18 minlesson

Try it yourself

Implement buildTableRowSelector:

  1. Accept orderId string.
  2. Return tr:has-text("${orderId}") >> button:has-text("Delete").

The editor has a worked example. Read it, tweak it, then press Mark as complete.

  1. page.getByRole(role, { name }): Accessible buttons, links, headings.
  2. page.getByLabel("Email"): Inputs associated with <label>.
  3. page.getByPlaceholder("Search"): Inputs without visible labels.
  4. page.getByText("Order Placed"): Static text.
  5. page.getByTestId("checkout-btn"): Dedicated QA test id.
javascript
// Locator Chaining & Filtering:
const targetCard = page.locator(".product-card")
  .filter({ hasText: "MacBook Pro" });
await targetCard.getByRole("button", { name: "Add to Cart" }).click();

Key Takeaways & Walkthrough Summary

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 resiliently without flakiness. Let's master locators!

Part of the Playwright + JS course (Playwright with JavaScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What is Playwright Strict Mode?

If a locator matches more than one element, Playwright throws a StrictModeError to prevent clicking the wrong element.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

JavaScript
Skip