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:
π Example:
π 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:
π Example:
π This will find .title elements inside .card, not the whole page.
π Key Differences
| Feature | cy.get() | .find() |
|---|---|---|
| Scope | Whole document (global) | Inside previously found element (local) |
| Starts From | Document root | A parent element |
| Use Case | First element selection | Nested/child element selection |
| Chainable? | No (starts a new chain) | Yes (used after get() or similar) |
π§ Real Example:
HTML:
✅ Using get():
✅ Using find():
✅ When to Use What
| Situation | Use |
|---|---|
| Finding any element globally | cy.get() |
| Finding elements inside a container | .find() |
| Selecting nested child elements | .find() |
| Starting a new element search | cy.get() |
π Bonus Tip:
Both can be used with CSS selectors, attributes, IDs, classes, etc.
✅ 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
Comments
Post a Comment