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.
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:
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:
// 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:
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: