TestingDocs.com logoTestingDocs.com
Automation learning lab
TestingDocs • Self-paced course

Playwright Automation
Self Study Guide

Start from zero. Learn JavaScript and TypeScript, automate browsers, and build reliable end-to-end tests.

60 chaptersBeginner friendlyHands-on practice
Playwright / Chapter 39 of 60~18 min • Beginner
Chapter 39Playwright

XPath and locator filtering

XPath selects DOM nodes using path expressions, but long structural paths can break after layout changes. Locator filter narrows matches using text or related locators. Playwright actions generally require exactly one matching element.

How it works

Step-by-step walkthrough

  1. Create two product rows
  2. Filter the target row
  3. Click its button

Example

TypeScript
import { test, expect } from '@playwright/test';

test('chapter 39 practice', async ({ page }) => {
  await page.setContent('<ul><li>Basic <button>Buy</button></li><li>Pro <button>Buy</button></li></ul>');
  const row = page.getByRole('listitem').filter({ hasText: 'Pro' });
  await row.getByRole('button', { name: 'Buy' }).click();
});
Expected result: Only the Pro button is clicked
💡 Point to remember
Prefer filtering semantic locators over absolute XPath.

Practice application screenshot

Actual screenshot of the TestingDocs task manager practice application
TestingDocs practice page, captured in Chromium.

✎ Your practice task

Locate the same row with locator('xpath=//li[contains(., "Pro")]') and compare.

Knowledge check

What does filter({ hasText: 'Pro' }) do?

🌐 Continue learning