In Cypress, to select the nth child element within a specific element, you can use .children() to retrieve all child elements and then use .eq(index) to select the child element at a specific index. Since indexes start at 0, to select the nth child element, you should use .eq(n-1). Here is a concrete example:
Assume the following HTML structure:
html<div class="parent"> <div class="child">Child 1</div> <div class="child">Child 2</div> <div class="child">Child 3</div> </div>
If you want to select the second child element within this parent element, you can write the Cypress test code as follows:
javascriptcy.get('.parent').children().eq(1).should('contain', 'Child 2');
In this example:
.get('.parent')selects the element with the classparent..children()retrieves all direct child elements of this parent element..eq(1)selects the second child element (index 1) among these children..should('contain', 'Child 2')is an assertion that checks if the selected element contains the text "Child 2".
To select the nth child element, subtract 1 from n and use .eq(n-1) since indexes are zero-based.
2024年6月29日 12:07 回复