Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 35 ยท Finding Elements

Selecting Elements in Cypress

Find elements in Cypress with cy.get, cy.contains, find, within, eq, first, parent and data-cy attributes, and learn how subjects, chaining and scoping work.

Before a test can click or check anything, it has to find the element. In Cypress, finding is done with a small set of commands: cy.get, cy.contains, .find, .within and a few helpers that narrow or move around a set of results. Learn these well and the rest of Cypress becomes easy to read.

This lesson explains each command, how they chain, how to scope a search to one part of the page, and why data-cy attributes are the recommended hook. At the end you build a small selector engine in a runnable stand-in to see what these commands do on a tree of elements.

The Cypress code is read-only because Cypress cannot run on this site. The stand-in is a simplified model of selecting and chaining over a fake element tree, not Cypress's real implementation.

cy.get: find by CSS selector

cy.get(selector) returns every element on the page that matches a CSS selector. It starts from the whole page.

JavaScript
// read-only
cy.get('h1')                      // by tag
cy.get('#cart')                   // by id
cy.get('.product')                // by class
cy.get('[data-cy=submit]')        // by attribute (recommended)
cy.get('ul.products > li')        // by structure
cy.get('input[type=email]')       // tag plus attribute

cy.get retries until at least one element exists (or the timeout ends). Whatever it finds becomes the subject passed to the next command in the chain.

cy.contains: find by text

cy.contains(text) finds an element by the text it shows, which is how a user finds things.

JavaScript
// read-only
cy.contains('Add to cart')                 // any element containing that text
cy.contains('button', 'Add to cart')       // a button containing that text
cy.contains(/^Checkout$/)                  // a regular expression

When there are several matches, contains yields the first one. Passing a selector first, as in cy.contains('button', 'Add'), narrows the search and is usually clearer than the text alone. It prefers the deepest element that holds the text, so you get the button and not the whole page. It is also case-sensitive by default.

find: search inside a subject

.find(selector) searches the descendants of the current subject, not the whole page.

JavaScript
// read-only
cy.get('.products').find('.price')          // prices only inside the product list
cy.get('#cart').find('.price')              // prices only inside the cart

This is the key to avoiding accidental matches. A page may have .price in five places; scoping tells Cypress which one you mean.

Narrowing and moving around

Once you have a set of elements, these commands pick from it or move through the tree:

Command Meaning
.first() / .last() The first or last element of the set
.eq(n) The element at zero-based position n; negative counts from the end
.filter(selector) Keep only elements that match the selector
.not(selector) Remove elements that match the selector
.parent() The parent of each element
.parents(selector) All ancestors, optionally filtered
.closest(selector) The nearest ancestor (or the element itself) that matches
.children() The direct children
.siblings() The other elements with the same parent
.next() / .prev() The adjacent sibling
JavaScript
// read-only
cy.get('.product').eq(1).find('h2').should('have.text', 'Lamp')
cy.contains('.product', 'Chair').find('button').click()
cy.get('[data-cy=error]').parent().should('have.class', 'field')

The second line is a very useful pattern: find the row by what it says, then act inside that row. Instead of numbering the third button on the page, you say "the product called Chair, and its button".

within: scope many commands at once

.within(callback) makes every cy.get and cy.contains inside the callback search only inside the subject.

JavaScript
// read-only
cy.get('form[data-cy=login]').within(() => {
  cy.get('[data-cy=email]').type('[email protected]')
  cy.get('[data-cy=password]').type('secret')
  cy.contains('button', 'Sign in').click()
})

Without within, you would repeat the form selector on each line. With it, the three commands are guaranteed to stay inside the login form, even if the page also has a newsletter form with an email field.

Chaining and subjects

Each command acts on the subject yielded by the one before:

JavaScript
// read-only
cy.get('.products')          // subject: the list
  .find('li')                // subject: its items
  .eq(2)                     // subject: the third item
  .find('button')            // subject: its button
  .click()                   // action on that button

Starting a new chain with cy. resets the subject to "the whole page". The command-queue lesson, How Cypress Commands Really Work, explains what happens behind the scenes.

flowchart TB
  P["page"] --> L["ul.products"]
  L --> I1["li Mug"]
  L --> I2["li Lamp"]
  L --> I3["li Chair"]
  I2 --> H["h2 Lamp"]
  I2 --> B["button Add"]
  I2 --> PR["span.price"]

cy.get('.products').find('li').eq(1).find('button') walks this tree: the list, its items, the second item, then its button.

Use data-cy attributes

CSS classes change when someone restyles the page. Text changes when someone edits copy. A dedicated attribute does neither, because its only job is to be found by tests:

HTML
<button class="btn btn-primary btn-lg" data-cy="add-to-cart">Add to cart</button>
JavaScript
// read-only
cy.get('[data-cy=add-to-cart]').click()

Cypress's own guidance favors attributes like data-cy, data-test or data-testid for this reason. The idea, plus alternatives that follow how users find things, is covered in Writing Selectors That Do Not Break.

A selector engine you can run

The stand-in below builds a fake page as a tree and implements a few commands: get, find, contains, first, eq, parent and within. It understands tag, #id, .class and [attr=value] selectors and descendant spaces. It is a tiny model, but it behaves like the real commands in the ways that matter: a chain starts with a subject, and each command produces a new one.

JS A tiny Cypress-style selector engine

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice three things in the output. First, the same .price selector gives different answers depending on the subject it starts from, which is why find and within matter. Second, contains('li.product', 'Chair') picks a whole row by its text, then find reaches inside it. Third, get('.missing') simply finds nothing; real Cypress would keep retrying for four seconds and then fail the test with an error that names the selector.

Common mistakes

  • Counting positions on the whole page, like cy.get('button').eq(4). Add a row or a banner and it points at the wrong thing. Find by meaning, then scope.
  • Selecting by styling classes such as .btn-lg or .mt-4.
  • Matching too much. cy.get('.price').click() fails when several elements match; narrow it with find, within or first.
  • Using find on the page. find needs a subject, so start with cy.get.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between cy.get('.price') and cy.get('#cart').find('.price')?

    cy.get always starts from the whole page (or the current within scope). find searches only the descendants of the current subject.
  2. 2. Which command finds the 'Checkout' button by its visible text, limited to buttons?

    cy.contains takes an optional selector first and then the text. cy.find does not exist at the top level; find only follows a subject.
  3. 3. What does .eq(-1) return?

    eq accepts negative numbers, which count from the end of the set.
  4. 4. Why are data-cy attributes recommended for selectors?

    A dedicated attribute exists only for tests, so redesigns and wording changes do not affect it.
  5. 5. What does .within(() => { ... }) do?

    within scopes the search, so identical-looking elsewhere on the page cannot be matched by accident.

Summary

  • cy.get finds elements by CSS selector from the whole page; cy.contains finds them by visible text.
  • .find searches inside the current subject; .within scopes a group of commands to a subject.
  • .first, .last, .eq, .filter, .parent, .closest and friends narrow or move through a set.
  • Chains pass a subject from one command to the next; starting a new cy. resets to the page.
  • Find a row by its text, then act inside it, instead of counting positions.
  • Prefer data-cy style attributes for stability.
  • The selector engine is a stand-in model, not Cypress's implementation.

Next: Locators in Playwright