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