javascriptcsscss-selectorscypress

how to pass values to :nth-child() css selector in cypress


I have a parent <div> that has many sub-elements. While traversing thorough them, if I need to select on of the child elements I will use this code:

cy.get(root-div > div:nth-child(1))

Then I have to get a second element, I will be using the following code:

cy.get(root-div > div:nth-child(2))

Can we make this div:nth-child(2) part dynamic something like this:

cy.get(root-div > div:nth-child(${0}))

i.e. insert the index values when we are calling this locator? So that locator becomes dynamic and can be used for all child elements.


Solution

  • You could create a JavaScript function for returning that string, and let it take in an indexing variable.

    const getNthChild(index) => {
      return `root-div > div:nth-child(${index})`
    });
    // In test
    cy.get(getNthChild(1));
    

    Additionally, if your cy.get() command yields multiple elements, the cy.eq() command can select an element at an index.

    cy.get('root-div > div').eq(1).should('be.visible')
    cy.get('root-div > div').eq(2).should('have.text', 'foo');
    

    Alternatively, you could create a custom Cypress command, although I think that is a little bit of an overkill.

    Cypress.Commands.add('getNthChild', (index) => {
      return cy.get(`root-div > div:nth-child(${index})`);
    });
    // In test
    cy.getNthChild(1);