How to Select Elements in Cypress: Syntax and Examples
cy.get() command with CSS selectors or attributes. You can also use cy.contains() to find elements by their text content. These commands let you target elements to interact with or assert in your tests.Syntax
The main command to select elements in Cypress is cy.get(). You pass a CSS selector string to it to find elements on the page. For example, cy.get('button') selects all <button> elements.
You can also use cy.contains() to select elements that contain specific text, like cy.contains('Submit').
Selectors can be tag names, classes, IDs, attributes, or combinations.
cy.get('<selector>') cy.contains('<text>')
Example
This example shows how to select a button by its class and click it, then select a link by its text and check its visibility.
describe('Element Selection Example', () => { it('selects elements and interacts', () => { cy.visit('https://example.cypress.io') cy.get('.btn-primary').click() // Select by class and click cy.contains('type').should('be.visible') // Select by text and assert visibility }) })
Common Pitfalls
Common mistakes include using overly broad selectors like cy.get('div') which select many elements and cause flaky tests. Avoid selecting by text that may change often. Also, do not chain commands without waiting for elements to appear.
Use unique selectors like data attributes (data-cy) for stable tests.
/* Wrong: Too broad selector */ cy.get('div').click() /* Right: Use data attribute for precise selection */ cy.get('[data-cy=submit-button]').click()
Quick Reference
| Command | Description | Example |
|---|---|---|
| cy.get() | Select elements by CSS selector | cy.get('.class-name') |
| cy.contains() | Select element by text content | cy.contains('Submit') |
| cy.get() with attribute | Select by attribute value | cy.get('[data-cy=login]') |
| cy.find() | Find child elements within a parent | cy.get('form').find('input') |