skip to Main Content

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.

2

Answers


  1. Cypress selectors use jQuery syntax. You can pass multiple selectors to cy.get by separating them with commas. For example, here’s how to select elements with id="UI-1" or id="UI-2":

    cy.get('#UI-1,#UI-2')
    
    Login or Signup to reply.
  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, just apply .first() command before .type(), or if you want to type into all of them use .each()

    cy.get('[id^="UI-"]')
      .each($el => {
        cy.wrap($el).type('abc')
      })
    

    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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search