| | |

Cypress 05 ๐ŸŒฒ Selectors โ€” cy.get, cy.contains, and data-cy Attributes

โฑ๏ธ Estimated read: 10 min | |

Cypress selectors are cy commands that find elements and return a chain for further commands. The two core selectors are cy.get(), which finds by CSS selector, and cy.contains(), which finds by text content. The recommended attribute for test-specific selectors is data-cy, which is stable across class-name and markup refactors and is scoped to the test rather than the styling. The choice of selector determines whether a test survives a redesign, and whether it fails with a clear “element not found” message or a confusing “clicked the wrong element” one.

This chapter covers the two selectors, the data-cy attribute convention, and the selector strategies that balance stability against accessibility. The sections that follow walk through cy.get, cy.contains, and the attribute patterns that keep tests resilient.

Key point: cy.get(selector) finds by CSS and retries until the element exists; cy.contains(text) finds the first element containing the text; data-cy is the recommended test attribute because it is stable, scoped to tests, and does not leak into styling.


a. cy.get and CSS selectors

cy.get(selector) takes a CSS selector and returns a chain for the first matching element (or all matching elements if .should('have.length') is used). The command retries until at least one element matches or the timeout expires. The selector can be an id (#email), a class (.btn), an attribute ([data-cy="submit"]), a tag (button), or a combination.

// By id
cy.get("#email").type("user@example.com");

// By class (discouraged; classes change with styling)
cy.get(".login-form").should("be.visible");

// By attribute (recommended for tests)
cy.get('[data-cy="submit"]').click();

// By tag and attribute
cy.get('button[type="submit"]').click();

// Multiple elements
cy.get("li").should("have.length", 3);

// Scoped within a parent
cy.get('[data-cy="user-list"]').find("li").should("have.length", 3);

The cy.get command is scoped to the document by default. To find an element inside a previously selected element, use .find() on the chain, not a second cy.get. The .find() searches within the subject of the previous command; cy.get searches the whole document.

// Scoped: find li inside the user list
cy.get('[data-cy="user-list"]').find("li").first().click();

// Not scoped: finds any li in the document
cy.get("li").first().click();

The .within() command is the block form of scoping. It runs a callback with the previous subject as the scope, so every cy.get inside it searches only within that element.

cy.get('[data-cy="login-form"]').within(() => {
  cy.get('[data-cy="email"]').type("a@b.com");
  cy.get('[data-cy="submit"]').click();
});

b. cy.contains and text matching

cy.contains(text) finds the first element in the document that contains the text. It accepts a string (substring match, case-sensitive by default) or a regular expression. The optional first argument is a selector that scopes the search.

// Find the first element containing "Welcome"
cy.contains("Welcome").should("be.visible");

// Scope to a selector
cy.contains("button", "Submit").click();

// Regex match
cy.contains(/Welcome, \w+/).should("be.visible");

// Chain to interact
cy.contains("a", "Forgot password?").click();

cy.contains is useful for text-driven assertions and for clicking elements whose text is the primary identifier. It returns the deepest element that contains the text, which is usually the element the user would click, but not alwaysโ€”a <span> inside a <button> is the deepest element containing the text, and clicking the span may not trigger the button’s handler.

The cy.contains("button", "Submit") form is the safer pattern for interactive elements: it scopes the text search to button elements, so it finds the button rather than its inner span.

// Safer: scope to the element type
cy.contains("button", "Submit").click();

// Less safe: may click an inner span
cy.contains("Submit").click();

c. data-cy and the test attribute convention

Cypress recommends the data-cy attribute for selectors that exist solely for testing. The attribute is not used by CSS or JavaScript, so it does not change when the styling changes, and it does not leak into the production behavior. The convention is documented in the Cypress best practices and is supported by the cypress-selectors plugin and the data-cy ESLint rule .

<button data-cy="submit">Place order</button>
cy.get('[data-cy="submit"]').click();

The attribute name is configurable with testIdAttribute (or cypress-selector-playground), but data-cy is the default in the Cypress ecosystem. The data-test, data-testid, and data-qa variants are used by other tools; the project should choose one and apply it consistently.

The data-cy attribute is stable but not accessible. A test that uses data-cy verifies the behavior but not the accessibility; a screen reader does not read data-cy, so a button with a data-cy and no accessible name passes the test and fails the user. The Cypress documentation recommends using the attribute in combination with the role-based queries where accessibility matters, but Cypress itself does not have Playwright’s getByRole โ€” the cypress-testing-library plugin provides it.

The ESLint rule eslint-plugin-cypress includes a no-unnecessary-waiting rule and a data-cy convention; the cypress-selectors plugin adds a data-cy helper. The choice of attribute is a convention, not a technical requirement, but the convention is what keeps the selectors consistent across the suite.


Complete Example Session

<!-- ============================================
     PART 1: THE MARKUP
     ============================================ -->
<form data-cy="login-form">
  <label for="email">Email</label>
  <input id="email" data-cy="email" type="email" />

  <label for="password">Password</label>
  <input id="password" data-cy="password" type="password" />

  <button type="submit" data-cy="submit">Sign in</button>
</form>

<ul data-cy="user-list">
  <li>Ana</li>
  <li>Ben</li>
  <li>Cleo</li>
</ul>
// ============================================
// PART 2: cy.get WITH data-cy
// ============================================
describe("login form", () => {
  it("fills and submits", () => {
    cy.visit("/login");

    cy.get('[data-cy="email"]').type("user@example.com");
    cy.get('[data-cy="password"]').type("password123");
    cy.get('[data-cy="submit"]').click();

    cy.url().should("include", "/dashboard");
  });
});

// ============================================
// PART 3: SCOPED SELECTORS
// ============================================
describe("user list", () => {
  it("has three users", () => {
    cy.visit("/users");

    // Scoped to the list, not the whole document
    cy.get('[data-cy="user-list"]')
      .find("li")
      .should("have.length", 3);
  });
});

// ============================================
// PART 4: cy.contains FOR TEXT
// ============================================
describe("navigation", () => {
  it("clicks the forgot password link", () => {
    cy.visit("/login");
    cy.contains("a", "Forgot password?").click();
    cy.url().should("include", "/reset");
  });
});

// ============================================
// PART 5: within() FOR BLOCK SCOPING
// ============================================
describe("within", () => {
  it("fills the form within its scope", () => {
    cy.visit("/login");
    cy.get('[data-cy="login-form"]').within(() => {
      cy.get('[data-cy="email"]').type("a@b.com");
      cy.get('[data-cy="submit"]').click();
    });
  });
});

The parts covered the markup with data-cy, cy.get with the attribute, scoped .find(), cy.contains with a selector, and .within() block scoping.


Quick Reference

Selectors

CommandMatchesRetry
cy.get(selector)CSS selectorYes
cy.contains(text)First element containing textYes
cy.contains(selector, text)Scoped text matchYes
.find(selector)Descendant of previous subjectYes
.within(fn)Block scopeN/A

Selector Strategies

StrategyStabilityAccessibility
data-cyHighNone
idMediumNone
aria-labelMediumHigh
Text contentMediumHigh
CSS classLowNone

data-cy Convention

ItemDetail
Attributedata-cy
PurposeTest-only selector hook
Alternativesdata-test, data-testid, data-qa
ScopeTests only, not styling

Best Practices

โœ… Do This:

// Use data-cy for test selectors
cy.get('[data-cy="submit"]').click();                         // โœ…

// Scope within a parent
cy.get('[data-cy="form"]').find('[data-cy="email"]');         // โœ…

// Scope text to an element type
cy.contains("button", "Submit").click();                      // โœ…

// Use within for blocks
cy.get('[data-cy="form"]').within(() => { ... });             // โœ…

โŒ Don’t Do This:

// Use CSS classes tied to styling
cy.get(".btn-primary").click();                               // โŒ

// Use cy.get for scoped search
cy.get('[data-cy="list"]'); cy.get("li"); // not scoped        // โŒ

// Click on text without scoping
cy.contains("Submit").click(); // may click a span             // โŒ

// Rely on data-cy for accessibility
// (screen readers do not read it)                            // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Selector breaks on redesignCSS class usedUse data-cy
Scoped search finds wrong elementcy.get instead of .findScope with .find or .within
Click does nothingText matched inner spanScope to element type
Multiple matchesSelector too broadAdd attribute or scope

Real-World Examples

1. cy.get by attribute

cy.get('[data-cy="email"]').type("a@b.com");

2. cy.get by id

cy.get("#email").type("a@b.com");

3. cy.contains with selector

cy.contains("button", "Submit").click();

4. cy.contains with regex

cy.contains(/Welcome, \w+/).should("be.visible");

5. .find scoped

cy.get('[data-cy="list"]').find("li").should("have.length", 3);

6. .within block

cy.get('[data-cy="form"]').within(() => { ... });

7. data-cy on an input

<input data-cy="email" />

8. data-cy on a button

<button data-cy="submit">Submit</button>

9. Custom attribute

// config: e2e: { testIdAttribute: "data-test" }

10. ESLint rule

eslint-plugin-cypress enforces data-cy convention

Visual

cy.get vs cy.contains

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  cy.get('[data-cy="submit"]')                           โ”‚
โ”‚    โ†’ finds by CSS attribute                             โ”‚
โ”‚    โ†’ retries until the element exists                   โ”‚
โ”‚                                                         โ”‚
โ”‚  cy.contains("button", "Submit")                        โ”‚
โ”‚    โ†’ finds by text content, scoped to button            โ”‚
โ”‚    โ†’ retries until an element contains the text         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Scoping

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  DOCUMENT                                               โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚
โ”‚  โ”‚ [data-cy="user-list"]                    โ”‚           โ”‚
โ”‚  โ”‚   <li>Ana</li>  โ—„โ”€โ”€ .find("li")          โ”‚           โ”‚
โ”‚  โ”‚   <li>Ben</li>                           โ”‚           โ”‚
โ”‚  โ”‚   <li>Cleo</li>                          โ”‚           โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚
โ”‚                                                         โ”‚
โ”‚  cy.get('[data-cy="user-list"]').find("li")             โ”‚
โ”‚  searches only inside the list                          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Selector Stability

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  HIGH STABILITY                                         โ”‚
โ”‚  data-cy="submit"                                       โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  survives class rename, markup refactor, redesign       โ”‚
โ”‚                                                         โ”‚
โ”‚  LOW STABILITY                                          โ”‚
โ”‚  .btn-primary > span                                    โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  breaks when the class changes or a wrapper is added    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

data-cy and Accessibility

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  data-cy="submit"                                       โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ”œโ”€โ”€โ–บ test finds the element                     โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ””โ”€โ”€โ–บ screen reader does NOT read it             โ”‚
โ”‚                                                         โ”‚
โ”‚  The test verifies behavior, not accessibility.         โ”‚
โ”‚  Use accessible names alongside data-cy when needed.    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
CSS selectorcy.get(selector)
Text selectorcy.contains(text)
Scoped textcy.contains(selector, text)
Descendant.find(selector)
Block scope.within(fn)
Test attributedata-cy
RetryBuilt into cy.get and cy.contains

Key takeaways:

  • cy.get finds by CSS and retries until the element exists. The selector can be an id, an attribute, a class, or a tag, and the choice determines whether the test survives a redesign .
  • cy.contains finds by text, scoped to a selector when needed. The scoped form cy.contains("button", "Submit") is safer for interactive elements because it finds the button rather than an inner span.
  • data-cy is the recommended test attribute. It is stable across styling changes and scoped to tests, but it does not verify accessibility. The test should use accessible names alongside it when accessibility matters.
  • .find and .within scope the search. cy.get searches the whole document; .find searches within the previous subject; .within runs a block of commands scoped to an element.
  • CSS classes are the least stable selector. A class tied to styling changes when the design changes, which makes the test fail for a reason unrelated to the behavior.

Remember: A selector is how the test finds the element, and the choice of selector determines whether the test is resilient to refactors. Use data-cy for test-specific hooks, scope with .find and .within to avoid matching the wrong element, and use cy.contains with a selector for text-driven interactions. The attribute is stable but not accessible; the test verifies behavior, and the accessible name is a separate concern.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!