These commands help you find related elements on a web page. cy.siblings() finds elements next to the current one. cy.closest() finds the nearest parent element that matches a condition.
cy.siblings() and cy.closest() in Cypress
cy.get(selector).siblings([filter]) cy.get(selector).closest(selector)
cy.siblings() finds all sibling elements of the current element. You can add a filter to narrow down results.
cy.closest() travels up the DOM tree to find the nearest ancestor matching the selector.
cy.get('.item').siblings() // Finds all siblings of elements with class 'item'
cy.get('.item').siblings('.active') // Finds siblings with class 'active' only
cy.get('.button').closest('form') // Finds the nearest form that contains the button
cy.get('#input').closest('.container') // Finds the nearest ancestor with class 'container'
This test visits a sample page. The first test finds siblings of the active list item and checks there are 3 siblings. The second test finds the closest form of an input and checks it has the expected class.
describe('Test siblings and closest commands', () => { beforeEach(() => { cy.visit('https://example.cypress.io/commands/traversal') }) it('checks siblings of a list item', () => { cy.get('.traversal-list > li.active') .siblings() .should('have.length', 3) }) it('finds closest form of an input', () => { cy.get('#inputEmail') .closest('form') .should('have.class', 'form-horizontal') }) })
Use cy.siblings() to find elements on the same level in the DOM tree.
Use cy.closest() to find the nearest parent element matching a selector.
Both commands help navigate the page structure to write better tests.
cy.siblings() finds elements next to the current one.
cy.closest() finds the nearest parent matching a selector.
These commands help you check related elements easily in tests.