Rayrun
← Back to Discord Forum

count nth children of css tag to use in for loop

ilovelamp69posted in #help-playwright
Open in Discord
ilovelamp69
ilovelamp69

If I have CSS tags: li.Bdrs\(3px\):nth-child(1) > div:nth-child(2) > a:nth-child(1) li.Bdrs\(3px\):nth-child(2) > div:nth-child(2) > a:nth-child(1) ... li.Bdrs\(3px\):nth-child(9) > div:nth-child(2) > a:nth-child(1)

How would I go about counting these so I could loop through them?

This thread is trying to answer question "How can I count CSS tags to loop through them?"

2 replies

Hello! maybe you can check this https://playwright.dev/docs/api/class-locator#locator-all

something like for (const li of await page.locator('li.Bdrs(3px)').all()) await li.click();

ilovelamp69
ilovelamp69

Thank you @apis3445 I went with using a f string and iterating through the nth-children until I got a timeout error which breaks me out of my while true loop.

Answer

Counting and Interacting with CSS Tags in Playwright

With Playwright, you can easily count CSS tags and loop through them using locators and methods. Let's say you want to count all the buttons on a page. Here's how you do it:

const buttonsCount = await page.locator('button').count();

The count() method returns the number of elements that match the given locator. In this case, it returns the count of all <button> elements on the page.

Now, let's say you want to interact with each button. You can loop through each element like this:

const buttons = await page.locator('button').toArray();

for (const button of buttons) {
  await button.click();
  // Add more operations as needed
}

Here, we first convert the locator result into an array using toArray(). Then, we iterate over each button element using a for...of loop and perform actions such as clicking on each button.

Remember, when working with multiple elements matching a locator, ensure that your locators uniquely identify your target elements. This helps avoid unintended clicks or interactions with unexpected elements when your web page changes.

For more insights on how to efficiently write Playwright test scripts, check out this blog post.

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

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 luc@ray.run.