Answer
Checking Element State in Playwright
Assertion Methods (Recommended — auto-retry)
These use expect() and automatically retry until the condition is true or the timeout is reached.
TypeScript
// Element is visible in the DOM and on screen
await expect(page.locator('.success-banner')).toBeVisible();
await expect(page.locator('.loading-spinner')).toBeHidden();
// Element exists in DOM (even if hidden)
await expect(page.locator('#hidden-field')).toBeAttached();
// Element is not in the DOM at all
await expect(page.locator('.deleted-item')).not.toBeAttached();
// Form field is enabled/disabled
await expect(page.getByRole('button', { name: 'Submit' })).toBeEnabled();
await expect(page.getByLabel('Email')).toBeDisabled();
// Checkbox state
await expect(page.getByLabel('Terms')).toBeChecked();
await expect(page.getByLabel('Newsletter')).not.toBeChecked();
// Input value
await expect(page.getByLabel('Email')).toHaveValue('user@test.com');
await expect(page.getByLabel('Email')).toBeEmpty();
Boolean Methods (For Conditional Logic — No Retry)
Use these when you need to make a decision based on element state.
TypeScript
// Returns true/false — no waiting
const isVisible = await page.locator('.notification').isVisible();
const isHidden = await page.locator('.loading').isHidden();
const isEnabled = await page.getByRole('button', { name: 'Next' }).isEnabled();
const isDisabled = await page.getByRole('button', { name: 'Submit' }).isDisabled();
const isChecked = await page.getByLabel('Terms').isChecked();
const isEditable = await page.getByLabel('Name').isEditable();
Use in Conditional Logic
TypeScript
test('handle optional cookie banner', async ({ page }) => {
await page.goto('/');
// Check if cookie banner exists before trying to dismiss
if (await page.locator('#cookie-banner').isVisible()) {
await page.getByRole('button', { name: 'Accept' }).click();
}
await page.getByRole('link', { name: 'Shop' }).click();
});
Count Elements
TypeScript
// How many elements match?
const count = await page.locator('li.item').count();
console.log(count); // 5
await expect(page.locator('li.item')).toHaveCount(5);
Summary Table
| Method | Type | Retries? | Returns |
|---|---|---|---|
expect(loc).toBeVisible() | Assertion | Yes | void (throws) |
expect(loc).toBeHidden() | Assertion | Yes | void (throws) |
expect(loc).toBeEnabled() | Assertion | Yes | void (throws) |
locator.isVisible() | Boolean | No | Promise<boolean> |
locator.isHidden() | Boolean | No | Promise<boolean> |
locator.isEnabled() | Boolean | No | Promise<boolean> |
locator.isDisabled() | Boolean | No | Promise<boolean> |
locator.isChecked() | Boolean | No | Promise<boolean> |
Best Practice: Use
expect()assertions for test verification. Use boolean methods only for conditional logic that drives test flow.
