Home > database >  How to get form control element by label?
How to get form control element by label?

Time:01-11

I have a form built from reusable components, such that each form control is generated with a unique id which is referenced by its label:

<label for="2346157937rfl5v">Complaint</label>
<div>
  <textarea id="2346157937rfl5v" [(ngModel)]="value"></textarea>
</div>

It's easy to use Cypress to identify the label element based on the text. But how can I then identify the associated form control element?

cy.contains('Complaint').???

I could just use .next().get('textarea'), but that seems too tied to the current implementation. Ideally there is some way to follow the link from the label.


Clarification: I want to identify the label element, get its for attribute, and then identify the textarea element using that id. This way the test isn't relying on the structure of the DOM.

CodePudding user response:

Few suggestions that could help based on the assumption that you want a cleaner way to access the textarea element.

  1. Using eq. If you have more than one text area and the position are fixed. You can directly access them.
cy.get('textarea').eq(0) //Gets the first text area
  1. I am assuming the id is re-generated with every compile. But If a part of your id remains constant, you can also use that to access your element.
cy.get('textarea[id*="2346157"]')
  1. Using next()
cy.contains('label','Complaint').next().next() //gets the textarea
OR
cy.get('label[for="2346157937rfl5v"]').next().next()

CodePudding user response:

I'm not sure this is the best way, but it does seem to work. I'd prefer something cleaner, so hopefully this illustrates the goal.

cy.contains('label', 'Complaint').then(label => {
  return cy.get(`#${label.attr('for')}`);
}).type('this is inside the textarea');

This approach identifies the label, then replaces the reference to the label with a reference to the element identified by the label's for attribute. So on the other side of .then(), the textarea is accessible.

  •  Tags:  
  • Related