Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to iterate over a <li> list in Playwright and click over each element?

I'm trying to iterate over a list of dynamic elements with Playwright, I've tried a couple of things already, but none have been working:

await this.page.locator('li').click();
const elements = await this.page.locator('ul > li');
await elements.click()
await this.page.$$('ul > li').click();
await this.page.click('ul > li');
const divCounts = await elements.evaluateAll(async (divs) => await divs.click());
this.page.click('ul > li > i.red', { strict: false, clickCount: 1 },)
const elements = await this.page.$$('ul > li > i.red')

elements.forEach(async value => {
  console.log(value)
  await this.page.click('ul > li > i.red', { strict: false, clickCount: 1 },)
  await value.click();
})
like image 276
Gabriel Costa Avatar asked Dec 06 '25 06:12

Gabriel Costa


2 Answers

Since https://playwright.dev/docs/api/class-locator#locator-element-handles doesn't have a good example on how to use .elementHandles().

Another way to solve this issue is as follows

const checkboxLocator = page.locator('tbody tr input[type="checkbox"]');
for (const el of await checkboxLocator.elementHandles()) {
  await el.check();
}
like image 144
Machtyn Avatar answered Dec 08 '25 20:12

Machtyn


I managed to do it with the following code:

test('user can click multiple li', async ({ page }) => {
  const items = page.locator('ul > li');
  for (let i = 0; i < await items.count(); i++) {
    await items.nth(i).click();
  }
})
like image 24
IslamTaha Avatar answered Dec 08 '25 20:12

IslamTaha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!