Skip to contentPlayForge

How do I count elements in Playwright?

Written by Jatin Thacker, Automation Architect · Updated

To check a count, use await expect(locator).toHaveCount(n), which retries until the number matches. To read the number into a variable, use await locator.count(), which returns how many elements match at that moment.

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

Counting is one of the few things you can do with a locator that matches many elements without breaking strict mode. Strict mode applies to actions that need one target, such as click(). count() is a multiple-element operation, so it works on any locator.

The two methods are for different jobs. toHaveCount() is a web-first assertion: it keeps checking until the count is right or the timeout runs out. That matters on pages that load lists after the first paint, like the catalog, whose product cards arrive from the mock API.

count() returns a number once. If it runs before the list has rendered, it returns 0, and nothing retries: called straight after page.goto() on this page, it does exactly that. The API reference says to prefer toHaveCount() when you are asserting, to avoid exactly that flakiness. Use count() when you need the value itself, such as a loop limit, and only after something has already waited for the list.

The example waits for 24 product cards with toHaveCount(), then reads the number with count(). It also counts a filtered subset, the two cards whose text contains Kettle.

qa-047.spec.js(https://practice.learnplayforge.com)
import { test, expect } from '@playwright/test'; test('count the product cards', async ({ page }) => { await page.goto('/catalog.html?mock=static&seed=42&autologin=1'); const cards = page.getByTestId('product-card'); // Assert a count: retries until there are 24 cards await expect(cards).toHaveCount(24); // Read a count: returns the number at this moment const total = await cards.count(); expect(total).toBe(24); // Count a filtered subset await expect(cards.filter({ hasText: 'Kettle' })).toHaveCount(2); });
Output
1 passed (2.6s)
Test yourself
The product cards load a moment after the page first paints. You want your test to fail unless the page shows exactly 24 cards, every run. Which line should you write?

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.