0

Pretty new to cypress (12.16) here and have a question:

I have a form that gets used in multiple areas of the app, I’m trying to turn filling it out into a command to centralize it in case we need to change variables, the issue is that I need to select an element which has an ID that can be either ‘UI-1’ or ‘UI-2’, and my JavaScript isn’t great - I’m wondering if there’s a way to build a selector that essentially looks for 'UI-1' and if it doesn’t find it then look for 'UI-2' and continue.

  • I originally thought of using something like Cy.get(‘[id=“UI-“]’) but the issue with that is there are actually two different elements that have two UI- ids, so I would have to specify UI-1 or UI-2 for the first set and UI-3 or UI-4 for the second – gopencyprep Jul 19 '23 at 21:36

1 Answers1

2

You can take the approach of partial attributes, since id="UI-1" is an attribute you are not limited to using #UI-1.

You can also use [id="UI-1"] and there are variations one of which is startsWith [id^="UI-"] which will find any id starting with UI-.

See this page for a complete list jQuery Attribute selectors

If you pick up multiple elements, use .each() to process them

cy.get('[id^="UI-"]')
  .each($el => {
    if ($el.attr('id') === 'UI-1' || $el.attr('id') === 'UI-2') {   
      cy.wrap($el).type('abc')
    } 
    if ($el.attr('id') === 'UI-3' || $el.attr('id') === 'UI-4') {   
      cy.wrap($el).type('def')
    } 
  })

or use a mapping

cy.get('[id^="UI-"]')
  .each($el => {
    const textForId = {
      'UI-1': 'abc',
      'UI-2': 'abc',
      'UI-3': 'def',
      'UI-4': 'def',
    }
    const id = $el.attr('id')
    cy.wrap($el).type(textForId[id])
  })

As for a custom command, it's pretty simple

Cypress.Commands.add('getElementsWithIdStarting_UI', () => {
  cy.get('[id^="UI-"]')
})

You can put it into the support folder to centralize the code (although I wouldn't bother with that, since global searching is pretty easy when you need to update the selector).