How to Find Your Elements by Text in Cypress
You can use the cy.contains
command in Cypress to find elements by their text content.
Copied to clipboard!
cy.contains('Text you are looking for')
You can also combine this command with cy.get
to narrow down your search and get a specific element with a text:
Copied to clipboard!
cy.get('button').contains('Learn more')
// In shorter form:
cy.contains('button', 'Learn more')
You can also pass two parameters to cy.contains
directly. One for the DOM selector, and a second string for the actual string content that you are looking for. The command can also be used case-insensitively by passing a configuration object with the matchCase
property in the following way:
Copied to clipboard! Playground
// Given the following HTML:
// <div>Case Sensitive</div>
// β This will fail
cy.contains('case sensitive')
// β
This will pass
cy.contains('case sensitive', { matchCase: false })
Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews