Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How in Cypress, find a card with a specific text and click on a specific button?

everyone!

Faced with a problem, I want to find the card I need in the list of cards guided by the text, and click in this card on the button

The idea is that would not go into details of nesting

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Enclosing a screenshot of how it looks like

enter image description here

html structure:

<div class="card">
  <span>name 1</span>
  <button data-test="more-menu"><svg /></button>
</div>
<div class="card">
  <span>name 2</span>
  <button data-test="more-menu"><svg /></button>
</div>
  <span>name 3</span>
  <button data-test="more-menu"><svg /></button>
</div>

Would like something like this

    cy.get('data-test=badge').then(($) => {
      cy.wrap($).contains(`${name} ${lastname}`).then(() => {
        cy.wrap($).find('[data-test=moreMenu]')
      })
    })

>Solution :

You can use the .contains for this. It gets the DOM element containing the text. And then use next() which gets the immediate sibling of the current element, something like this:

cy.contains('span', 'Name 1').next().click()

In case you have a nested structure inside your card class, you can use first parent() which will go to the card parent element and then use within to scope the next commands inside the same card class, something like this:

cy.contains('span', 'Name 1').parent('.card').within(() => {
  cy.get('[data-test="more-menu"]').click()
})

Now We have used parent() once since the .card is available one level up from span. In case you have more levels you have to add more parent().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading