Cypress get the ID of some element

Viewed 1457

I am trying to obtain the ID of some element in Cypress. Because it's ID randomly changes (yes it is strange but it is angular).

E.g. I have a <button id="dropdown-1" class="someclass"><span>Click here</button>

As I can't rely on that ID, because after I do some actions on the page it becomes to dropdown-2 etc., I want to know, what is the current ID name.

I tried something like:

cy.get('button > span').contains('Click here').find("id");

but seems that is not the correct way.

I also tried:

  cy.get('button > span').contains('Click here')
  .invoke('attr', 'id')

this works not as well.

1 Answers

You can use a combination of text and a selector which has the non-changing part of your id value. Something like:

cy.contains('button[id*="dropdown-"]', 'Click here').invoke('attr', 'id')

Now you can use use the id value in two ways.

  1. Directly after extraction:
cy.contains('button[id*="dropdown-"]', 'Click here')
  .invoke('attr', 'id')
  .then((id) => {
    cy.log(id) //prints id
  })
  1. Save it in alias .as and use it later:
cy.contains('button[id*="dropdown-"]', 'Click here')
  .invoke('attr', 'id')
  .as('idValue')
cy.get('@idValue').then((idValue) => {
  cy.log(idvalue) //prints id
})
Related