How do I get the text of every item in a list in Playwright?
Written by Jatin Thacker, Automation Architect · Updated
This answer is one piece of Chapter 15: Dialogs, Drag and Tables.
- Drag and Drop, Sliders & Range Inputs
- Modals, Dialogs, Toasts & Alerts
- Tables, Pagination & Infinite Scroll
- Practice and interview questions: Form Interactions
Most of the time you want the text of a list in order to check it. For that, one assertion does the whole job: toHaveText() with an array checks that the locator matches that many elements and that each one has the expected text, in order. It retries like every web-first assertion, so it waits for the list to finish rendering.
Sometimes you need the strings themselves: to sort them, to compare two reads of a table, or to pick a value for the next step. allTextContents() returns an array of strings, one per matching element. It reads once and does not wait, so a list that is still loading can give you a short or empty array. The API reference recommends toHaveText() whenever you are asserting. If you do read, wait first, for example with toHaveCount().
The example uses the catalog's Recommended list. At ?seed=42 its six items are in a fixed order, which the array assertion checks. The test then reads the same six names with allTextContents() and checks one is present. allInnerTexts() is the variant that returns each element's innerText instead of its textContent.
import { test, expect } from '@playwright/test';
test('read the text of every recommended item', async ({ page }) => {
await page.goto('/catalog.html?mock=static&seed=42&autologin=1');
const items = page.getByTestId('recommended-item');
// To check the list: one assertion that retries, in order
await expect(items).toHaveText([
'Aurora Pour-Over Kettle',
'Halcyon Burr Grinder',
'Northwind Knock Box',
'Quarry Ceramic Dripper',
'Cinder Drip Scale',
'Tidewater Cold Brew Carafe',
]);
// To use the values in code: an array of strings, read once
const names = await items.allTextContents();
expect(names).toHaveLength(6);
expect(names).toContain('Northwind Knock Box');
});1 passed (1.6s)
await items.allTextContents() return?Related questions
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