How to Perform Actions on Multiple Elements in Playwright

Better Stack Team
Updated on February 27, 2024

In most cases, you'll be writing tests that performs an action on one element at a time. However, if you need to perform an action on multiple elements at once (such as clicking on several items in a list), you can do it as follows:

 
test('user can click multiple list items', async ({ page }) => {
  const items = page.locator('ul > li');

  for (let i = 0; i < await items.count(); i++) {
    await items.nth(i).click();
  }
})

Once you've selected all the items using the appropriate locator method, you can iterate over the found items using and then perform the relevant action in the body of the loop.

Thanks for reading, and happy coding!

🔭 Want to automate and scale your Playwright end-to-end tests?

Head over to Better Stack and start monitoring in 5 minutes.