Playwright: How to search for an element that has a specific empty tag in the element tree?

Viewed 2890

How to search for an element that has a specific empty tag in the element tree in Playwright tests (using their test-runner)?

I have tried an empty text filter (obviously not the best idea)

// variant 1
page.locator(`[aria-label="label name"].has(span:text-is(""))`);
// variant 2
page.locator(`[aria-label="label name"].has(div[role="button"] span[text=""])`);

but got error

locator.textContent: Unexpected token "" while parsing selector "[aria-label="label name"]"

The only solution that works for me is to check each text content using JS, for example:

const locator = page.locator('div[role="button"] >> span');
const elementsCount = await locator.count();
for(let i = 0; i < elementsCount; i++) {
  const spanTextContent = await locator.nth(i)?.textContent();
  return spanTextContent === '' ? locator.nth(i) : null;
}

Another example that gives Unexpected token "" while parsing selector error:

    locator = page.locator(`body:has(div[class="L3eUgb"] >> a >> text="About")`);
    console.log(`locator.count(): ${await locator.count()}`);
1 Answers

It seems that you're mixing a little bit wrongly CSS selectors and custom Playwright's pseudo-classes.

This should work for you:

page.locator('div[role="button"] >> span >> text=""')

UPDATE:

page.locator(`body:has(div[class="L3eUgb"]) >> a >> text="About"`)

enter image description here

Related