qatester123
qatester123

Reputation: 143

How to get an element that has a dynamic selector in Cypress

My script has a button which leads to an external site where I need to input some information in a field.

I'm not able to find a way to select that field because it's within an iframe and also has a dynamically generated ID. That ID has 2 characters at the end that are always consistent.

So far I've tried:

cy.get('#*_2'); --> Trying to use a wildcard to click on the element that has a _2 at the end but it does not work

I've tried using a cy.get('input[data-collect-as="input"]') --> It's not able to find this element either.

Any help would be appreciated.

enter image description here

Upvotes: 2

Views: 12071

Answers (2)

Alapan Das
Alapan Das

Reputation: 18650

You can use the pattern attribute value as well.

cy.get('input[pattern="[0=9]*"]')

Upvotes: 1

user16003578
user16003578

Reputation:

The shorthand id selector #myid can only be used with the exact value, but id is still an attribute so you can use an attribute selector with a wildcard

cy.get('[id$="_2"]')         // $= means value ending with 

There's a bunch variations, see Selectors - Attribute


The other approach you tried should work like this

cy.get('div[data-collect-as="input"] input') 

This gets a child input with ancestor div[data-collect-as="input"] - the space denoting two separate elements and the relationship is ancestor -> descendant.

You can add more precision

cy.get('div[data-collect-as="input"] > div.wrp > input') 

where the > indicates a parent-child relationship.

Upvotes: 5

Related Questions