0

I am new to Cypress and I want to find the element whose id is dynamic but id have some specific text. example.

...
<div class="col2">
 <button id="random-city-name_type-125" class="btn-secondary">
  <span>
   <i class="icon">::before</i>
   "some city"
  <span>
 <button>
</div>
<div class="col3">
 <button id="random-account-number_type-119" class="btn-secondary">
  <span>
   <i class="icon">::before</i>
   "abc text"
  <span>
 <button>
</div>
...

Here, I want to find the button whose id contains account-number and have text inside span "abc text" and want to click on that button which open popup.

I tried following.

cy.visit("localhost:5000");
cy.wait(4000)
cy.get('[id^=account-number-]').find('span').contains("abc text").click(); //This gives me error.

But, it gives error that element not found. Any help would be greatly appreciated.

ketan
  • 19,129
  • 42
  • 60
  • 98

3 Answers3

1

The issue comes from using ^ with your CSS selector. The ^ symbol means that the matching element must begin with the selector given. Instead, you can use * which will check if the selector contains (not limiting to beginning or ending with.)

cy.get('[id*="account-number"]')
  .find('span')
  .contains('abc text')
  .click();

Additionally, you'll only need the .find() between the .get() and the .contains() if you specifically need to have the span found. Using cy.get(...).contains(...) uses the yielded .get() element as the parent that Cypress uses for .contains(). (Alternatively, you could also include the span in the .get() selector

cy.get('[id*="account-number"]') // or .get('[id*="account-number"] span')
  .contains('abc text')
  .click();
agoff
  • 5,818
  • 1
  • 7
  • 20
0

You can use xpath

cy.xpath("//div[@class='col3']//button//span//i").click()
Alex77
  • 27
  • 4
  • How can I find `account-number` from id using Xpath? – ketan Feb 01 '23 at 11:55
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 01 '23 at 19:25
0

You can use within to scope your next commands inside your id section.

cy.get('[id*="random-account-number"]').within(() => {
  cy.get('span').should('include.text', 'abc text')
})
Alapan Das
  • 17,144
  • 3
  • 29
  • 52