Home > Back-end >  Playwright: how to know which selector fired when waiting for multiple?
Playwright: how to know which selector fired when waiting for multiple?

Time:07-12

Imagine waiting for multiple selectors like this:

const element = await page.waitForSelector("div#test div#test2 div#test3 button, div#zest div#zest2 div#zest3 button")

How do I tell whether the first selector matched, or the second one? Do I need to $ twice and then compare the element?

CodePudding user response:

That selector completes when one of the two selectors is found.

If you need both, you'll have to await on the specific selector (twice).

CodePudding user response:

You can separate the selectors using a comma, which acts as an OR condition, and then extract the innerText of those elements. And then on the basis of the inner text, determine which selector was available.

const elementText = await page
  .locator(
    'div#test div#test2 div#test3 button,div#zest div#zest2 div#zest3 button'
  )
  .innerText()
if (elementText == 'some text') {
  //Do something
}

In case you have an attribute-value pair that is unique to both, you can do like this:

const elementText = await page
  .locator(
    'div#test div#test2 div#test3 button,div#zest div#zest2 div#zest3 button'
  )
  .getAttribute('id')
if (elementText == 'zest') {
  //Do something
}
  • Related