To iterate through a list of elements in a for loop using @playwright/test, you can use the $$
function to get an array of elements matching a specific selector. Then, you can use a for
loop or Array.prototype.forEach()
to iterate through the elements.
Here's an example:
import { test, expect } from '@playwright/test';
test('Iterate through elements', async ({ page }) => {
await page.goto('https://ray.run/');
// Get an array of elements matching the selector
const elements = await page.$$('.some-selector');
// Iterate through the elements using a for loop
for (const element of elements) {
// Perform actions or assertions on each element
const text = await element.textContent();
console.log(text);
}
// Alternatively, use forEach() to iterate through the elements
elements.forEach(async (element) => {
// Perform actions or assertions on each element
const text = await element.textContent();
console.log(text);
});
});
In this example, we first navigate to the https://ray.run/
website. Then, we use the $$
function to get an array of elements matching the .some-selector
selector. We iterate through the elements using a for
loop and a forEach()
loop, performing actions or assertions on each element.
For more tips on writing efficient @playwright/test scripts, check out Tips for Writing Efficient Playwright Test Scripts.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].