Select elements based on layout in Cypress

Viewed 75

I am looking for a solution that can work like the following code in Playwright.

page.click('input:right-of(:text("Username"))');

By using this command in Playwright, the input element on the right side of text Username will be clicked. I searched for a while but found that there seemed to be no handy equivalents in Cypress. Are there any approaches that can enable the possibility to select elements based on their positional relationships?

1 Answers

I think you can use

cy.contains('Username')    // === :text("Username")
  .next()                  // === :right-of(<previous subject>)
  .click()

There may be subtle differences, like .contains() is a partial match and .next() is the next sibling in the DOM, not necessarily "right-of" by x coordinates.


You can add-in cypress-testing-library which has

cy.findByLabelText('Username').type('myname')

I haven't used it, but semantically seems to be what you are aiming for. Would be useful if relative positions change in mobile mode (e.g labels above).

A while back I implemented custom commands to assert relative positions of elements, as we were getting a lot of CSS regressions, but it's quite fiddly.

Related