Answer
Clicking Elements in Playwright
Basic Click
TypeScript
// Using role locator
await page.getByRole('button', { name: 'Submit' }).click();
// Using text locator
await page.getByText('Login').click();
// Using CSS locator
await page.locator('#submit-btn').click();
// Using label-associated form button
await page.getByLabel('Search').click();
What Happens During click()
Playwright automatically:
- ✓Waits for the element to be visible in the DOM
- ✓Waits for it to be enabled (not disabled)
- ✓Waits for it to be stable (not animating)
- ✓Scrolls it into view if needed
- ✓Moves the mouse to the center of the element
- ✓Fires
mousedown,mouseup,clickevents
Click Options
TypeScript
// Click with a modifier key
await page.locator('#item').click({ modifiers: ['Shift'] }); // Shift+Click
await page.locator('#item').click({ modifiers: ['Control'] }); // Ctrl+Click
// Click at a specific position within the element
await page.locator('#canvas').click({ position: { x: 100, y: 50 } });
// Click with a delay (simulate slow user)
await page.locator('#btn').click({ delay: 100 });
// Force click (bypass actionability checks — use carefully)
await page.locator('#hidden-btn').click({ force: true });
// Click with custom timeout
await page.locator('#btn').click({ timeout: 10000 });
Double Click
TypeScript
await page.locator('#cell').dblclick();
Right Click (Context Menu)
TypeScript
await page.locator('#item').click({ button: 'right' });
Middle Click
TypeScript
await page.locator('#link').click({ button: 'middle' });
Click Inside a Specific Parent
TypeScript
// Click a button within a specific modal
const modal = page.locator('.modal');
await modal.getByRole('button', { name: 'Confirm' }).click();
Full Example
TypeScript
import { test, expect } from '@playwright/test';
test('form submit', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('user@test.com');
await page.getByLabel('Password').fill('password123');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL('/dashboard');
});
