πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 62 of 100
Mechanics
Advanced

What is the difference between waitForSelector and locator actions?

The Answer

`waitForSelector` is a legacy API that returns an `ElementHandle`. Modern Playwright replaces it with `locator.waitFor()` which is integrated with the locator API and returns the locator itself for chaining.

Deep Dive Explanation

The fundamental issue with `waitForSelector` is that it returns an `ElementHandle` β€” a frozen reference to a DOM node. If the DOM updates between the wait and the action (e.g., list re-renders), the handle becomes stale. Locators always re-query, so they're always fresh.

example.spec.ts
// LEGACY: waitForSelector (returns ElementHandle - avoid)
const el = await page.waitForSelector('.result');
await el.click(); // ElementHandle can go stale!

// MODERN: locator.waitFor() (returns locator - preferred)
const locator = page.locator('.result');
await locator.waitFor({ state: 'visible' });
await locator.click(); // Re-queries DOM on click

// Even better: Just use Web-First assertions
await expect(page.locator('.result')).toBeVisible();
await page.locator('.result').click();