We can find a child element of a parent element in Cypress in several ways. You can use CSS or XPath selectors, or Cypress commands such as .find(), .children(), and .within().
Below are example scripts to find the second child list element (<li>) from an unordered list (<ul>).
- Using Css Selector: We can find a child element with a CSS selector using
:nth-child().
Example Code:
cy.get(‘ul > li:nth-child(2)’).click();
Explanation:
-
li:nth-child(2)→ selects the second<li>element inside the<ul>. -
ul→ selects the unordered list. -
>→ means direct child.
2.Using XPath: We can find a child element using an XPath expression in Cypress.
To use XPath selectors, make sure you’ve installed the Cypress XPath plugin.
Setup (if not already done):
2.1. Install the plugin:
npm install -D cypress-xpath
2.2. Add the following line to your cypress/support/e2e.js (or commands.js in older versions):
require(‘cypress-xpath’);
Example Code:
cy.xpath(“(//ul/li)[2]”).click();
Explanation:
//ul/li→ selects all<li>elements under all<ul>elements.[2]→ selects the second<li>element (XPath uses 1-based indexing)..click()→ performs a click action on that element.
3. Using find method:
- We can use the
.find()command to fetch child elements from a parent element. .find()searches for descendants within the selected parent element.
Example Code:
cy.get(‘div’).find(‘ul’).first().find(‘li’).eq(1).click();
4. Using children method: We can find a child element in Cypress using the .children() command.
This method selects only the direct child elements (not deeper descendants) of the located parent.
Example Code:
cy.get(“ul”).children(“li”).eq(1).click();
5. Using within() command: We can find a child element using the .within() command in Cypress.
The .within() command limits all Cypress commands inside its callback to the scope of the selected parent element.
This is useful when you want to make sure Cypress only searches inside a specific section of the DOM.
Example code:
cy.get(‘ul’).within(() => {
cy.get(‘li’).eq(1).click();
});