I am using this locator to try to get a list of elements on the page: await page.locator('input[id="remove"]').all()
but it returns an empty list.
However, when I do something like await page.locator('input[id="remove"]').click()
I get an error because the locator resolves to 3 elements. If that's the case, why aren't those 3 elements getting into my list when I use all()
?
I feel like I must be missing something fundamental about the way all()
works.
For reference, I'm trying to locate the three remove
inputs in the .cell-remove
classes inside of the td
elements (see attached screenshot of the html). I need to get all of them and then delete the last 2 in the list, which I think I can figure out - but I need to be able to grab those elements first.
Thanks for any help you can give me!
This thread is trying to answer question "Why does the locator `all()` return an empty list when it resolves to 3 elements?"
Related Ask AI answer for "What is the reason for the `all()` function of a locator in @playwright/test returning an empty list even when it resolves to multiple elements?".
all()
Function in @playwright/testThe all()
function of a locator in @playwright/test doesn't wait for elements to match the locator. It immediately returns whatever is present on the page at that moment. If your page's elements change dynamically, calling locator.all()
can produce unpredictable results.
Here's how you can ensure accurate results:
Before calling locator.all()
, make sure all elements have finished loading. You can use Playwright's waiting mechanisms, like waiting for a specific condition or event.
await page.waitForSelector('.my-element');
const elements = locator.all();
The all()
function returns an array of locators pointing to respective elements. You can interact with each element using Playwright's methods.
const elements = locator.all();
elements.forEach(async (element) => {
await element.click();
});
In conclusion, if locator.all()
returns an empty list when you expect multiple elements, it's likely due to dynamic changes in the elements. Always wait for all elements to load before calling locator.all()
.
For more insights on handling flaky tests in Playwright, check out this blog post.
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].