Skip to contentPlayForge

How do I select an element by data-testid in Playwright?

Written by Jatin Thacker, Automation Architect · Updated

Use page.getByTestId('your-id') to select an element by its dedicated test attribute. By default, Playwright matches elements whose data-testid attribute equals the provided string.

This answer is one piece of Chapter 9: Locators I: What the User Sees.

  • getByRole and the Accessible Name
  • getByText, getByLabel, getByPlaceholder, getByTestId
  • Strict Mode — One Locator, One Element

Playwright provides the getByTestId() locator for cases where user-facing locators like role or text are insufficient, such as dynamic content, icon-only buttons, or custom layout containers with non-standard markup.

By default, page.getByTestId('cart-link') targets elements with data-testid="cart-link". If your codebase standardizes on a different attribute like data-test or data-cy, you can reconfigure the locator globally in playwright.config.ts by setting testIdAttribute: 'data-test'.

While test IDs provide resilience against visual redesigns and translated text, Playwright recommends prioritizing user-facing locators like getByRole() and getByLabel() where possible. User-facing locators ensure your automation validates accessibility semantics, while test IDs serve as dependable structural anchors for complex components.

test-id.spec.js(https://practice.learnplayforge.com)
import { test, expect } from '@playwright/test'; test('select element by data-testid attribute', async ({ page }) => { await page.goto('/catalog.html?mock=static&seed=42&autologin=1'); const searchForm = page.getByTestId('catalog-search-form'); await expect(searchForm).toBeVisible(); const cartLink = page.getByTestId('cart-link'); await expect(cartLink).toBeVisible(); });
Output
1 passed (2.1s)
Test yourself
An element has markup <div data-testid="cart-summary" class="summary-box">. How do you locate it using Playwright's test id helper?

Practised in the full course: the drill The button you can see.

See the chapter

AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.

163 lessons · 226 drills · start free

← All questions

Training a team? Talk to us.