Cypress Locators: Get vs Find

Cypress Locators: get() vs find()

When writing tests with Cypress, locating elements on a web page is key.
Two of the most used commands are:

  • cy.get()

  • .find()

Although they may seem similar, they have different purposes and scopes.


πŸ”Ή 1. cy.get() — Global Selector

πŸ“Œ What it does:

  • Searches for elements in the entire DOM (the whole page).

  • Starts from the root of the document.

✅ Syntax:

cy.get('selector')

πŸ“‹ Example:

cy.get('.card')

πŸ‘‰ This will find all elements with the class .card in the whole page.


πŸ”Ή 2. .find() — Scoped Selector

πŸ“Œ What it does:

  • Searches for elements inside another element.

  • Starts from the previously selected element (like a child selector).

✅ Syntax:

cy.get('parentSelector').find('childSelector')

πŸ“‹ Example:

cy.get('.card').find('.title')

πŸ‘‰ This will find .title elements inside .card, not the whole page.


πŸ” Key Differences

Featurecy.get().find()
ScopeWhole document (global)Inside previously found element (local)
Starts FromDocument rootA parent element
Use CaseFirst element selectionNested/child element selection
Chainable?No (starts a new chain)Yes (used after get() or similar)

🧠 Real Example:

HTML:

<div class="card"> <h2 class="title">Title 1</h2> </div> <div class="card"> <h2 class="title">Title 2</h2> </div>

✅ Using get():

cy.get('.title') // Finds both "Title 1" and "Title 2"

✅ Using find():

cy.get('.card').first().find('.title') // Finds only "Title 1" inside the first .card

✅ When to Use What

SituationUse
Finding any element globallycy.get()
Finding elements inside a container.find()
Selecting nested child elements.find()
Starting a new element searchcy.get()

πŸ›  Bonus Tip:

Both can be used with CSS selectors, attributes, IDs, classes, etc.

cy.get('[data-cy="login-button"]') cy.get('#main').find('input[type="email"]')

✅ Summary:

  • Use **cy.get()** to locate elements from the entire page.

  • Use **.find()** to search within an element found previously.

 

Learn Cypress Course in Hyderabad

Read More




Comments

Popular posts from this blog

Tosca System Requirements and Installation Guide (Step-by-Step)

How to Install Selenium for Python Step-by-Step

Tosca Commander: A Beginner’s Overview