Is there any way I can use index inside a cy.get('k")?

Viewed 48

I have a table like structure where each cell takes some input. The html tag has id something like id="code[0].name", id="code[0].age", ..., and so on.Similarly, id="code[1].name", id="code[1].age", ..., and so on

Now, in cypress, I want to perform something like this,

namesToFetch.forEach( (el,k) => {
   cy.get('[id=code[k].name]').type(name)

My questions is, how to use the k'th index inside the cy.get()?

2 Answers

You can use:

namesToFetch.forEach( (el,k) => {
   cy.get(`[id=code[${k}].name]`).type(name)

Or, you could use:

namesToFetch.forEach( (el,k) => {
   cy.get('[id=code[' + k + '].name]').type(name)

You can wild-card the matching selector

cy.get('input[id$="name"]')  // elements with id attribute ENDING WITH name
  .each(($el,idx) => {
    cy.wrap($el).type(namesToFetch[idx])
  })
Related