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
You could create a JavaScript function for returning that string, and let it take in an indexing variable.
Additionally, if your
cy.get()
command yields multiple elements, thecy.eq()
command can select an element at an index.Alternatively, you could create a custom Cypress command, although I think that is a little bit of an overkill.
Since you are dealing with the children elements, you can use the
.children(selector)
command and specify thenth
one either inside it’s selector or following it with.eq()
Some options are
I would not use a function or a custom command as it adds complexity but adds no extra clarity.