Cypress contains() is used to identify the one or more browser element[s] based on the text.
Example –
![](https://qavalidation.com/wp-content/uploads/2021/07/cypressContains_qavbox.jpg)
In Cypress, The link with text “SignUp Form” can be identified as
cy.contains('SignUp').click()
or
cy.get('.myhmenu').contains('SignUp').click()
The above command will locate the element with text ‘SignUp’ based on a parent element .myhmenu
Note – contains() can be used directly with cy object and also can be used with chain commands.
Some more contains() syntaxes –
contains('sometext') //see the example above
contains(selector, 'sometext')
contains(selector, 'sometext', options)
Examples –
contains(selector, ‘sometext’)
For the demo site – https://qavbox.github.io/demo/listitems/
cy.contains('[id=\'subgroup\']', 'List Item 1')
Cypress will first search for the element with text “List Item 1″, then it will search for parent element with id=”subgroup”
![](https://qavalidation.com/wp-content/uploads/2021/07/cypress_contains_selector_qavbox-674x1024.jpg)
Let’s see another example –
cy.contains('[id=\'mygroup\']', 'List Item 1')
This above line will search for List Item 1 and then will find if there is an element with id=mygroup.
![](https://qavalidation.com/wp-content/uploads/2021/07/cypress_contains_selector_qavbox1-661x1024.jpg)
Examples with options –
Option | Default | Description |
---|---|---|
matchCase | true | Check case sensitivity |
log | true | Displays the command in the Command log |
timeout | defaultCommandTimeout | Time to wait for .contains() to resolve before timing out |
includeShadowDom | includeShadowDom config option value | Whether to traverse shadow DOM boundaries and include elements within the shadow DOM in the yielded results. |
cy.visit('https://qavbox.github.io/demo/signup') cy.contains('Full name', {matchCase: false}) //ignore the case sensitivity
Like matchCase option, we can use any of the options from the above table with cy.contains() method.