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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github