skip to Main Content

I am having a parent Div that has many sub element, while traversing thorough them if I need to select some child element I will do,

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

And then I have to get 2nd element I will be doing like

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

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

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

And then pass the values when we are calling this locator? So that locator becomes dynamic and can be used for all child elements.

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. Since you are dealing with the children elements, you can use the .children(selector) command and specify the nth one either inside it’s selector or following it with .eq()

    Some options are

    // give me 2nd child that is a div
    cy.get('root-div').children('div').eq(1).should(...
    
    // same, using `eq()` inside the selector
    cy.get('root-div').children('div:eq(1)').should(...
    
    // traverse all the children, with index
    cy.get('root-div').children((child, index) => {
      cy.wrap(child).should(...
    

    I would not use a function or a custom command as it adds complexity but adds no extra clarity.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search