1. Introduction to Playwright TypeScript Locators
Locators are one of the most important concepts in Playwright automation testing. Whenever an automation engineer interacts with a web application, they need to identify elements such as buttons, text fields, dropdowns, links, checkboxes, and tables.
Playwright provides a powerful locator system that helps testers identify and interact with these web elements reliably.
For QA Automation Engineers, SDETs, and developers, understanding Playwright TypeScript locators is essential for creating stable end-to-end automation scripts.
Unlike traditional browser automation approaches, Playwright locators support automatic waiting, retryability, and strictness checks. These features help reduce common automation problems such as element-not-found errors and timing issues.
In this tutorial, you will learn:
- What Playwright locators are and why they are important.
- How auto-waiting and locator retryability work.
- Different built-in locator methods.
- How to use CSS and XPath selectors.
- How to handle multiple and dynamic elements.
- How to create reusable locators.
- How to debug common locator errors.
We will use practical TypeScript examples so you can apply these concepts directly to your automation framework.
2. What Are Locators and Why Use Them?
A locator is an object that identifies one or more elements on a web page. Playwright uses locators to perform actions such as clicking, filling text fields, selecting options, and verifying element states.
Consider a login page containing:
- Username textbox.
- Password textbox.
- Login button.
- Forgot password link.
To automate this page, Playwright must identify each element before interacting with it.
Example:
import { test, expect } from ‘@playwright/test’;
test(‘Login page automation’, async ({ page }) => {
await page.goto(‘https://example.com/login’);
await page.getByLabel(‘Username’).fill(‘admin’);
await page.getByLabel(‘Password’).fill(‘admin123’);
await page.getByRole(‘button’, {
name: ‘Login’,
}).click();
await expect(page).toHaveURL(/dashboard/);
});
In this example:
- getByLabel() identifies the username and password fields.
- getByRole() identifies the login button.
- fill() enters text.
- click() performs the button action.
- toHaveURL() verifies navigation.
Why Are Playwright Locators Important?
| Benefit | Explanation |
| Reliability | Supports automatic waiting and retryability |
| Readability | User-facing locators make tests easier to understand |
| Reusability | Locators can be stored and reused |
| Maintainability | Reduces dependence on brittle selectors |
| Debugging | Provides useful errors when elements cannot be identified |
3. Role of Auto-Waiting and Locator Retryability
One of the most useful features of Playwright is automatic waiting.
In traditional automation frameworks, testers often use explicit waits to ensure elements are available before interacting with them.
Playwright automatically waits for relevant actionability conditions before performing supported actions.
For example:
await page.getByRole(‘button’, {
name: ‘Submit’,
}).click();
Before clicking, Playwright checks whether the element is:
- Visible.
- Stable.
- Enabled.
- Able to receive pointer events.
If these conditions are not satisfied, Playwright waits until they are satisfied or the action timeout expires.
What Is Locator Retryability?
Playwright locators are evaluated when an action or assertion is performed. They can locate an element again when the page changes.
Example:
const message = page.getByText(‘Payment successful’);
await expect(message).toBeVisible();
The assertion automatically retries until the message becomes visible or the assertion timeout expires.
This is particularly useful when an application loads information asynchronously.
What Is Strict Mode?
Playwright uses strictness for operations that expect a single element.
Consider:
await page.getByText(‘Login’).click();
If multiple matching elements exist, Playwright throws a strict mode violation instead of arbitrarily selecting one.
You should make the locator more specific:
await page.getByRole(‘button’, {
name: ‘Login’,
}).click();
This improves test reliability and avoids unexpected interactions.
4. Built-in Playwright Locator Methods
Playwright provides several built-in locator methods. These methods help identify elements using their roles, text, labels, placeholders, and test IDs.
For reliable automation, prefer user-facing locators such as roles and labels whenever possible.
4.1 getByRole()
getByRole() identifies elements based on their accessible role and accessible name.
It is one of the recommended locator methods because it represents how users and assistive technologies understand a page.
Example:
test(‘Locate button using role’, async ({ page }) => {
await page.goto(‘https://example.com/login’);
const loginButton = page.getByRole(‘button’, {
name: ‘Login’,
});
await loginButton.click();
});
Other examples:
page.getByRole(‘heading’, { name: ‘Dashboard’ });
page.getByRole(‘link’, { name: ‘Home’ });
page.getByRole(‘checkbox’, { name: ‘Remember me’ });
page.getByRole(‘textbox’, { name: ‘Username’ });
You can also use options such as exact: true when you need an exact accessible-name match.
page.getByRole(‘button’, {
name: ‘Login’,
exact: true,
});
4.2 getByText()
getByText() identifies elements based on their visible text content.
Example:
test(‘Verify success message’, async ({ page }) => {
await page.goto(‘https://example.com’);
const message = page.getByText(‘Login successful’);
await expect(message).toBeVisible();
});
You can also use partial text:
page.getByText(‘Login’, { exact: false });
This is useful for validating confirmation messages, notifications, and application content.
4.3 getByLabel()
getByLabel() identifies form controls using their associated accessible labels.
Example:
test(‘Enter user details’, async ({ page }) => {
await page.goto(‘https://example.com/register’);
await page.getByLabel(‘Full Name’).fill(‘John Smith’);
await page.getByLabel(‘Email Address’).fill(‘john@example.com’);
});
This method works particularly well with accessible form labels.
4.4 getByPlaceholder()
getByPlaceholder() identifies input fields using their placeholder attributes.
Example:
test(‘Search products’, async ({ page }) => {
await page.goto(‘https://example.com’);
await page.getByPlaceholder(‘Search products’).fill(‘Laptop’);
await page.keyboard.press(‘Enter’);
});
This is useful for search boxes and forms where placeholder text clearly identifies the field.
4.5 getByTestId()
getByTestId() identifies elements using a dedicated test attribute.
For example, an application may contain:
<button data-testid=”submit-order”>
Place Order
</button>
test(‘Submit order’, async ({ page }) => {
await page.goto(‘https://example.com/checkout’);
await page.getByTestId(‘submit-order’).click();
});
You can configure a different test ID attribute in playwright.config.ts:
use: {
testIdAttribute: ‘data-qa’,
}
Then you can use:
page.getByTestId(‘submit-order’);
Built-in Locator Comparison
| Locator | Identifies elements using | Typical usage |
| getByRole() | Accessible role and name | Buttons and links |
| getByText() | Visible text | Messages and labels |
| getByLabel() | Associated form label | Form fields |
| getByPlaceholder() | Placeholder attribute | Search boxes |
| getByTestId() | Test-specific attribute | Stable test hooks |
5. CSS and XPath Selectors in Playwright
Although built-in locators are recommended, CSS and XPath selectors are also supported.
These selectors are useful when an application does not provide accessible names or when you need to locate complex elements.
5.1 CSS Selectors
CSS selectors identify elements using IDs, classes, attributes, and relationships.
<input id=”username” class=”user-input” />
<button class=”login-button”>Login</button>
Playwright TypeScript:
test(‘Use CSS selectors’, async ({ page }) => {
await page.goto(‘https://example.com/login’);
await page.locator(‘#username’).fill(‘admin’);
await page.locator(‘.login-button’).click();
});
Common CSS selectors:
| Selector | Purpose |
| #username | Element with an ID |
| .login-button | Element with a class |
| input[type=”email”] | Element with an attribute |
| div > button | Direct child button |
| form input | Input inside a form |
5.2 XPath Selectors
XPath identifies elements based on their position and relationships within the HTML document.
Example:
test(‘Use XPath selector’, async ({ page }) => {
await page.goto(‘https://example.com/login’);
await page.locator(
‘//input[@id=”username”]’
).fill(‘admin’);
await page.locator(
‘//button[text()=”Login”]’
).click();
});
You can also explicitly use the XPath prefix:
page.locator(‘xpath=//button[@type=”submit”]’);
CSS vs XPath vs Built-in Locators
| Type | Best use |
| Built-in locators | User-facing and accessible elements |
| CSS selectors | Stable attributes and application-specific structures |
| XPath | Complex relationships when other locators are unsuitable |
Interview tip: Do not claim that XPath is always slower or that CSS is always faster. Locator quality, selector stability, and application structure matter more. Prefer readable, maintainable locators.
6. Locator Filtering, Chaining, and Handling Multiple Elements
Real-world applications often contain repeated buttons, product cards, menu items, and table rows.
Playwright provides methods such as filter(), locator(), nth(), first(), and last() to handle these elements.
6.1 Using filter()
The filter() method narrows down matching elements using conditions such as text or another locator.
Example:
test(‘Select a specific product’, async ({ page }) => {
await page.goto(‘https://example.com/products’);
const product = page.locator(‘.product-card’).filter({
hasText: ‘Laptop’,
});
await product.getByRole(‘button’, {
name: ‘Add to Cart’,
}).click();
});
This finds the product card containing Laptop and clicks its Add to Cart button.
6.2 Using Locator Chaining
You can create a locator relative to another locator.
const product = page.locator(‘.product-card’);
const price = product.locator(‘.price’);
await expect(price).toContainText(‘₹’);
This is useful when the same element structure appears multiple times on a page.
6.3 Handling Multiple Elements
Use count() to determine how many elements match.
test(‘Count navigation links’, async ({ page }) => {
await page.goto(‘https://example.com’);
const links = page.getByRole(‘link’);
const totalLinks = await links.count();
console.log(‘Total links:’, totalLinks);
expect(totalLinks).toBeGreaterThan(0);
});
You can also use:
const firstLink = links.first();
const lastLink = links.last();
const secondLink = links.nth(1);
Remember that nth() uses zero-based indexing. Use it only when the element order is meaningful and stable.
7. Handle Dynamic Elements and Nested Components
Modern web applications frequently update their content dynamically.
For example:
- Search suggestions appear while typing.
- Notifications appear after submitting forms.
- Product lists update after filtering.
- Dropdown options load from an API.
- Dashboard widgets display asynchronous data.
Example: Handle Dynamic Search Suggestions
test(‘Select dynamic search suggestion’, async ({ page }) => {
await page.goto(‘https://example.com’);
const search = page.getByPlaceholder(‘Search products’);
await search.fill(‘Laptop’);
const suggestion = page.getByRole(‘option’, {
name: ‘Laptop Pro’,
});
await expect(suggestion).toBeVisible();
await suggestion.click();
});
The test waits for the dynamic suggestion to appear before clicking it.
Example: Locate Nested Components
Consider an application with multiple employee cards.
test(‘Verify employee department’, async ({ page }) => {
await page.goto(‘https://example.com/employees’);
const employee = page.locator(‘.employee-card’).filter({
hasText: ‘John Smith’,
});
await expect(
employee.getByText(‘Engineering’)
).toBeVisible();
});
The test first identifies John Smith’s card and then checks the department inside that card.
This approach avoids accidentally matching the same department text elsewhere on the page.
8. Practical Form Automation Using Multiple Locator Strategies
Let’s create a complete example that uses different Playwright locator methods in one registration test.
Assume a registration page contains:
- Full Name field.
- Email field.
- Password field.
- Terms and Conditions checkbox.
- Register button.
- Success message.
Complete TypeScript Example
Create tests/registration.spec.ts:
import { test, expect } from ‘@playwright/test’;
test(‘Verify user registration’, async ({ page }) => {
await page.goto(‘https://example.com/register’);
// Locate fields using labels
await page.getByLabel(‘Full Name’).fill(‘John Smith’);
await page.getByLabel(‘Email Address’)
.fill(‘john@example.com’);
// Locate password using placeholder
await page.getByPlaceholder(‘Enter password’)
.fill(‘Password@123’);
// Locate checkbox using role
await page.getByRole(‘checkbox’, {
name: ‘I accept the terms and conditions’,
}).check();
// Locate button using role
await page.getByRole(‘button’, {
name: ‘Register’,
}).click();
// Verify registration confirmation
await expect(
page.getByText(‘Registration successful’)
).toBeVisible();
});
Expected Result
Expected test result
The test should:
- Open the registration page.
- Enter the user’s details.
- Accept the terms and conditions.
- Submit the registration form.
- Verify the success message.
This example demonstrates how different locator strategies can work together in a real-world automation scenario.
The URL, field labels, and confirmation message are sample values. Replace them with your application’s actual elements.
9. Common Locator Errors and Debugging Techniques
Even experienced automation engineers sometimes face locator failures.
Understanding the cause helps you resolve failures without adding unnecessary waits.
Error 1: Locator Not Found
Reason: The locator does not match any element.
Example:
await page.locator(‘#user-name’).fill(‘admin’);
The actual application might use #username.
Solution: Inspect the HTML and correct the locator. Prefer accessible labels or roles when available.
Error 2: Strict Mode Violation
Reason: A locator matches multiple elements when an operation expects one.
Example:
await page.getByText(‘Submit’).click();
There may be multiple Submit elements.
Solution:
await page.getByRole(‘button’, {
name: ‘Submit’,
}).click();
Alternatively, narrow the locator to a specific form or container.
Error 3: Element Is Not Visible
Reason: The element exists but is hidden or covered by another element.
Solution: Check whether a modal, loading overlay, or responsive layout is affecting visibility. Use an appropriate locator for the visible element.
Error 4: Element Is Not Enabled
Reason: The application has disabled the element, perhaps until required fields are completed.
Solution:
const submitButton = page.getByRole(‘button’, {
name: ‘Submit’,
});
await expect(submitButton).toBeEnabled();
await submitButton.click();
Error 5: Timeout Error
Reason: The element did not become actionable or the expected condition was not satisfied within the timeout.
Solution: Check the locator, application response, navigation, and network behavior before increasing the timeout.
Debugging with Playwright Inspector
Run:
npx playwright test –debug
You can also use:
await page.pause();
This opens the Playwright Inspector when running in an appropriate debugging environment.
For locator inspection, use:
npx playwright test –ui
The UI mode helps you inspect test execution, locator behavior, and failures.
10. Best Practices for Playwright TypeScript Locators
Follow these recommendations when developing professional automation frameworks.
- Prefer getByRole(): Use accessible roles and names for buttons, links, and other interactive elements.
- Use getByLabel(): Identify form fields through their associated labels.
- Use meaningful test IDs: Request stable data-testid attributes when user-facing locators are insufficient.
- Avoid brittle XPath: Do not depend unnecessarily on deeply nested DOM structures.
- Reuse locator objects: Store frequently used locators in Page Object Model classes.
- Avoid unnecessary fixed waits: Prefer Playwright auto-waiting and web-first assertions.
- Handle multiple matches carefully: Use filter() and specific parent locators.
- Use strictness correctly: Avoid blindly selecting the first matching element.
- Keep locators readable: Use descriptive variable names.
- Debug before changing timeouts: Identify why the element is unavailable instead of simply increasing the timeout.
Example: Reusable Locators with Page Object Model
import { Page, Locator } from ‘@playwright/test’;
export class LoginPage {
readonly username: Locator;
readonly password: Locator;
readonly loginButton: Locator;
constructor(private readonly page: Page) {
this.username = page.getByLabel(‘Username’);
this.password = page.getByLabel(‘Password’);
this.loginButton = page.getByRole(‘button’, {
name: ‘Login’,
});
}
async login(user: string, pass: string): Promise<void> {
await this.username.fill(user);
await this.password.fill(pass);
await this.loginButton.click();
}
}
This approach keeps locator definitions in one place and makes the framework easier to maintain.
11. Frequently Asked Questions (FAQs)
Q1. How do I get started with Playwright TypeScript locators?
Install Playwright using npm init playwright@latest, select TypeScript, create a test file, and practise locator methods such as getByRole(), getByText(), and getByLabel().
Q2. Is Playwright TypeScript locators suitable for beginners?
Yes. Beginners can start with built-in locators such as getByRole(), getByText(), and getByPlaceholder(). These methods are easy to understand and help create readable test scripts.
Q3. What are the benefits of Playwright TypeScript locators?
They provide automatic waiting, retryability, reusable element identification, improved readability, and better integration with TypeScript-based automation frameworks.
Q4. What is the difference between locator() and getByRole()?
locator() supports CSS, XPath, and other selector strategies. getByRole() identifies elements using accessible roles and names, making tests more user-focused.
Q5. What is strict mode in Playwright?
Strict mode ensures that operations expecting a single element do not silently select one when multiple elements match. It helps identify ambiguous locators.
Q6. Can we use XPath in Playwright TypeScript?
Yes. Playwright supports XPath through page.locator(). However, built-in locators and stable CSS selectors are generally easier to maintain.
Q7. How do you handle multiple elements with the same locator?
Use count(), first(), last(), nth(), or filter() depending on the scenario. Prefer filtering by meaningful content rather than relying on element position.
Q8. Are Playwright locators better than Selenium locators?
Playwright provides a modern locator system with auto-waiting and retryability. Selenium also supports multiple locator strategies. The main difference is how the frameworks handle element interactions and synchronization.
