Home > OS >  Cypress find element with id contains and have span
Cypress find element with id contains and have span

Time:01-31

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

...
<div >
 <button id="random-city-name_type-125" >
  <span>
   <i >::before</i>
   "some city"
  <span>
 <button>
</div>
<div >
 <button id="random-account-number_type-119" >
  <span>
   <i >::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.

CodePudding user response:

You can use xpath

cy.xpath("//div[@class='col3']//button//span//i").click()

CodePudding user response:

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')
})
  • Related