Understanding Cypress Children()

Learn how to use the Cypress Children() command to find child elements of a specific parent. Run Cypress Tests on real devices with BrowserStack Automate

Get Started free
Home Guide Cypress – Children

Cypress – Children

By Siddharth Murugan, Community Contributor -

Cypress is a front-end testing tool built for the modern web. It provides solutions for end-to-end testing, component testing, accessibility testing, UI coverage, and more.

Cypress can test anything that runs in a browser. Behind Cypress is a Node server process. Cypress and the Node process constantly communicate, synchronize, and perform tasks on behalf of each other.

Access to both parts (front and back) allows you to respond to your application’s events in real-time while working outside the browser for tasks requiring higher privileges.

What is Cypress-Children ()?

The method children() in Cypress is used to get the child elements present in the particular parent element.

For example, you may have a list element/table element and want to interact with its child elements.

Now, with the help of the children() method, you can interact with the other nested elements inside the parent element. This method gets the children of each DOM element within a set of DOM elements.

Syntax of Cypress-Children ()

The Cypress method children() has the syntax which looks as below,

cy.get(parentSelector).children(childSelector, options) 
  • The childSelector is optional, but the parentSelector should be present to extract its nested elements.
  • The options are also not mandatory, and two options can be added.
  • The children() method cannot be used independently (i.e., cy.children()) and should always be chained after cy.get() or cy.find().
  • The children() method can indeed be chained with other methods like .eq(), .each(), .should(), etc.
  • You can chain the children() method with any other relevant Cypress commands, but avoid chaining it in logically incorrect ways.

Arguments with Cypress-Children ()

The children() method in Cypress has two options: log and timeout.

OptionDefault valueDescription
logtrueThis displays the commands in the command log
timeoutBy default, it takes the timeout mentioned in the configuration fileTime to wait for the children() method elements.

Use cases of Cypress-Children ()

Below are the key use cases of cypress childre:

  • Validating the child element count: To verify the page’s structure, check if a parent element has the expected number of child elements.
cy.get(selector).children().should(‘have.length’,8)
  • Iterate through the child element: When you need to perform actions on several child elements directly nested within a particular parent element, like selecting multiple items from a dropdown menu or clicking on multiple links within a navigation bar.
  • Testing complex nested elements: When dealing with deeply nested elements, .children() can be combined with other DOM traversal methods like .eq() or .first() to pinpoint specific child elements within a complex hierarchy.

How to use Cypress-Children ()

Here is an example of how to take children from the parent element ul.

Consider an HTML page with the below tags,

<html></html>

<body>

 <ul class="parent-element">

 <li class="child-1">I'm a child element 1</li>

 <li class="child-2">I'm a child element 2</li>

 </ul>

</body>

</html>

To get the two listed elements inside the parent element, you should mention the following,

cy.get('.parent-element').children().should('have.length', 2)

With the above command, you should be able to get the two nested children elements and validate the length of the two elements present.

Examples of using Cypress-Children ()

So far, what you have seen is just a demonstration. Now, you will get hands-on experience using Cypress using the children() method.

Validating the child element count

  • To validate the count of the child element, visit the BrowserStack demo website.
  • Look for the navigation menu and validate the count as 3.
  • Execute the code below.

Validating the child element count

describe('template spec', () => {

  it('test case', () => {

  //Visiting the BrowserStack demo website

cy.visit('https://bstackdemo.com/')

    //Getting the three navigation bar elements and validating their count to be three

// cy.get('.space-x-4').children().should('have.length',3)

})

  })

Validate child element count output

Iterate through the child element: There may be a scenario in which you should iterate through each element and find out its text.

Take a look at the code below to iterate through the navigation bar child element of the BrowserStack demo website.

describe('template spec', () => {

  it('test case', () => {

cy.visit('https://bstackdemo.com/')

    //Iterating through child element and looking for the element with text as Orders

cy.get('.space-x-4').children().each(($element) =>{

  if($element.text() == "Orders")

  {

   cy.log("Element found")

  }

})

})

  })

Iterate through the child element

Testing complex nested elements: When you get complex nested elements, you must click the element with index as 1.

For such scenarios also, you can combine with other methods and click the respective element like below code,

describe('template spec', () => {

  it('test case', () => {

cy.visit('https://bstackdemo.com/')

// clicking the first element from the list of the navigation menu

cy.get('.space-x-4').children().eq(1).click()

})

  })

Testing complex nested elements

Common errors while using Cypress-Children ()

Below are some common errors while using Cypress children:

  • Always ensure that the selector you are using to apply the children() method is correct. If you have any issues, use Cypress Selector Playground.
  • The children () method can select only the direct children elements.
  • Make sure to club the children() method with the get() method, as it cannot be directly used with the cy command.

Best Practices for Cypress-Children ()

Here are some best practices for using Cypress-Children:

  • If the child element is visible after some time, use
cy.get().should('be.visible').children()
  • Correctly chain children() with other Cypress commands like .each() to iterate through the child elements and perform actions on them.
  • Not chaining children() correctly with other Cypress commands like .should() or .each() can lead to errors if you try to perform actions on the children without first selecting them properly.

BrowserStack Automate Banner

Run Cypress tests on Real Browsers and Devices with BrowserStack

Testing web and mobile applications on real devices and browsers ensures a seamless user experience, platform compatibility, and reliable real-world performance. BrowserStack provides a robust platform with access to 3,500+ real devices and browsers for comprehensive testing.

  • BrowserStack Automate lets you test native and hybrid apps on various mobile and tablet devices housed in secure data centers.
  • Run Cypress tests across an extensive list of browsers and devices, with support for CI integration and Local Testing to streamline workflows.
  • Testing on real devices and browsers helps ensure uniform application behavior and validates its performance and security under real user conditions.

Talk to an Expert

Conclusion

The children() command in Cypress is a powerful tool for navigating and asserting the immediate child elements of a parent in the DOM. It allows you to directly filter and interact with specific child elements, providing better control and precision in your tests.

Use children() when you focus on immediate children, and remember to differentiate it from find() when deeper traversal is required. This ensures clarity and accuracy in your test scripts, enhancing overall test maintainability.

Useful Resources for Cypress

Understanding Cypress

Use Cases

Tool Comparisons

Tags
Automation Testing Cypress

Featured Articles

Cross Browser Testing with Cypress : Tutorial

Cypress Automation Tutorial

Automation Tests on Real Devices & Browsers

Seamlessly Run Automation Tests on 3500+ real Devices & Browsers