How to select nth item inside select element in cypress

JD. picture JD. · Jun 8, 2018 · Viewed 36.2k times · Source

say I have the HTML:

<select name="subject" data-testid="contact-us-subject-field">
  <option value="What is this regarding?">What is this regarding?</option>
  <option value="Partnerships">Partnerships</option>
  <option value="Careers">Careers</option>
  <option value="Press">Press</option>
  <option value="Other">Other</option>
</select>

Selecting an option with a known value, such as 'Careers' is as easy as:

cy.get('[data-testid="contact-us-subject-field"]').select('Careers');

How do I select the nth option in this field, regardless of its value?

Answer

Arnaud P picture Arnaud P · Jun 8, 2018

Update

As pointed out by @dpstree in the comments, this doesn't answer the original question. Please see more recent answers for a complete solution.

Original

By using eq

cy.get('tbody>tr').eq(0)    // Yield first 'tr' in 'tbody'
cy.get('ul>li').eq(4)       // Yield fifth 'li' in 'ul'