How to Find Your Elements by Text in Cypress

How to Find Your Elements by Text in Cypress

Ferenc Almasi β€’ 2022 August 17 β€’ Read time 1 min read
  • twitter
  • facebook

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:

Learn Cypress with Educative
How to Find Your Elements by Text in Cypress
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.