Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress - difference between find() and within() methods

What are the differences are there between using either of these methods:


cy.get('.wtv').find('.sub-wtv');

cy.get('.wtv').within(() => {cy.get('.sub-wtv');});

From the documentation
https://docs.cypress.io/api/commands/find.html
https://docs.cypress.io/api/commands/within.html

They both let us work with a "sub DOM", in which we can do whatever we would like, like searching a specific element and assert it.

like image 513
notihs Avatar asked Mar 13 '26 10:03

notihs


1 Answers

.find() is used for single search of an element, but only limits your actions to that element

.within() lets you to change the scope of searching the sub elements and call them directly with cy.get('subelementSelector'), and also work with them. The down side is, you can`t call elements from outside the scope of the parent element.

The third way is then. cy.get('elementSelector').then(element=>{//some code}) - this allows you to pass the element to a function for usage. You can search sub elements within with cy.get(element).find('subelementSelector'). Also you can use the usual commands for elements located outside the parent element scope. This has longer sintax, but greater scope.

Edit: To clarify .find() - allows a single usage of an element .within(passedFunction()=>{}) - changes the scope for DOM elements of the passedFunction to just child elements .then(element=>{}) - doesn't change the scope, but creates a JQ variable of the variable, that is available to use in the then function cy.get('parentSelector childSelector') - is the css way of getting the same result as .find()

like image 118
Rosen Mihaylov Avatar answered Mar 15 '26 22:03

Rosen Mihaylov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!