How to select nth item inside select element in cypress
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?
Solution 1:
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'
Solution 2:
In the particular context of selecting the nth option
, this may be appropriate:
cy.get('select[name=subject] > option')
.eq(3)
.then(element => cy.get('select[name=subject]').select(element.val()))
Solution 3:
Based on solution from Miguel Rueda, but using prevSubject
option:
Cypress.Commands.add(
'selectNth',
{ prevSubject: 'element' },
(subject, pos) => {
cy.wrap(subject)
.children('option')
.eq(pos)
.then(e => {
cy.wrap(subject).select(e.val())
})
}
)
Usage:
cy.get('[name=assignedTo]').selectNth(2)
Explanation:
- Using
children('option')
and.eq(pos)
traverse children of select to specific element. - Call
select
method with value of selected element.