Playwright: how to know which selector fired when waiting for multiple?

Viewed 222

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?

2 Answers

You are using , separator which is the "multiple" operator.

To see which element you have, check the id of the parent.

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

const parent = await element.$('xpath=..')
if (parent) {
  const id = await parent.getAttribute('id')
  console.log('id', id)

  expect(id).to.eq('test3')    // passes in test3 is present

  // or if test3 is not present
  expect(id).to.eq('zest3')    // zest3 passes if test3 is not present
}

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