Cypress children command

Profile picture for user devraj

Using Cypress Children command you can get the children of each DOM element within a set of DOM elements. The querying behavior of this command is the same as the JQuery children method where the children() method in JQuery returns all direct children of the selected element.

In Cypress children command yield single DOM element or set of elements. This command cannot be chained to cy object directly.

Syntax

You can see In syntax we have a selector which is used to filter elements and options. Children command accepts 2 options logs and timeout. 

.children()
.children(selector)
.children(options)
.children(selector, options)

Example

For demo we will consider autopract website top menu icons.

cypress children command demo

Here is the HTML

cypress children command demo html

You can see in above screenshot, for parent ul we have 3 li elements, for demo we will assert no of children for ul parent and will click on search icon which is the first li.

  it.only('children demo', ()=> {

    cy.visit("/")
    cy.get('button.close').click()

    // find all the children
    cy.get('div.icon-nav > ul').children().should('have.length', 3)

    //find particular children
    cy.get('div.icon-nav > ul').children('.mobile-search').click()
   
  })