When using Cypress for frontend testing, retrieving child elements of a specific parent element is a common requirement. Cypress provides multiple methods to achieve this, and I will introduce several commonly used methods along with relevant examples.
Method One: Using .find()
The .find() method can search for child elements within a selected DOM element. This is one of the most straightforward methods.
Example:
Consider the following HTML list with multiple list items:
html<div id="todo-list"> <ul> <li class="item">Learn JavaScript</li> <li class="item">Read Cypress documentation</li> <li class="item">Write test cases</li> </ul> </div>
To select all <li> elements under the <ul>, you can do the following:
javascriptcy.get('#todo-list').find('li').should('have.length', 3);
Here, cy.get('#todo-list') first selects the element with ID todo-list, and then .find('li') finds all child elements li.
Method Two: Using .children()
The .children() method retrieves all direct child elements of an element, which also applies to obtaining child elements of a specific parent element.
Example:
Using the same HTML structure:
javascriptcy.get('ul').children().should('have.length', 3);
Here, cy.get('ul') first selects the ul element, and then .children() retrieves its direct child elements (i.e., all li elements).
Method Three: Using .eq() to Select a Specific Child Element
Sometimes we only need to retrieve a specific child element from a set of child elements, and we can use the .eq() method, which allows us to select a specific child element by index.
Example:
javascriptcy.get('ul').find('li').eq(1).should('contain', 'Read Cypress documentation');
Here, cy.get('ul').find('li') first finds all li child elements, .eq(1) selects the second li element (index starts from 0), and then verifies that it contains the text "Read Cypress documentation".
Conclusion
By using these methods, we can flexibly and efficiently retrieve and manipulate child elements of specific parent elements in Cypress, supporting complex DOM structure testing. Each method is suitable for different scenarios, so you can choose the appropriate method based on your needs.