October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

How to Use Web Selectors in Cypress

Choose Cypress selectors by test intent: use data attributes for stable hooks, text queries when wording matters, and scoped queries to target the right container.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use cy.get() with a dedicated data-* attribute for stable test hooks, cy.contains() when the text itself is part of what you want to test, and within() or .find() to limit a query to the right part of the page. Cypress retries queries and their chained assertions while waiting for the expected state.

Choose a selector that matches what the test is checking

Ask whether changing the element’s visible wording should make the test fail. If the wording is the behavior under test, find the element by text. If not, use a dedicated test attribute so a copy or styling change does not unnecessarily break the test.

As an Amazon Associate I earn from qualifying purchases.

Selector approach Use it when Trade-off
Dedicated data-* attribute You need a stable hook independent of styling and ordinary text changes. Your application team must add and maintain the attribute.
Text with cy.contains() The wording is meaningful and a wording change should fail the test. Copy changes can break the test; string matches may match a substring.
Role and accessible name The test should locate a control through the semantics and name available to users. Requires a Testing Library query such as findByRole().
Class, ID, tag, or name A project-specific case makes that selector appropriate. Generic tags and styling classes may be broad or brittle; treat IDs and semantic names as selective options.

Cypress recommends data attributes for context and isolation from CSS or JavaScript changes. Its examples use conventions including data-cy, data-test, data-testid, and data-qa. Pick one convention for a project and use it consistently. See Cypress best practices.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a test attribute for a stable hook

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

// Cypress test
cy.get('[data-cy="submit"]').click()

cy.get() accepts CSS selectors, including attribute selectors. This example targets the control without making the test depend on its label text.

Use text when text is the behavior

cy.contains('button', 'Submit').click()

This test intentionally depends on the button wording. The explicit button selector also limits candidates to buttons.

Find elements with Cypress queries

cy.get(selector)

In ordinary use, cy.get() searches from the Cypress root, usually the application document. It can find one or multiple elements:

cy.get('[data-cy="todo-item"]').should('have.length', 5)
cy.get('input, textarea, select').should('have.length', 3)

You can also retrieve an alias with cy.get('@alias'). A DOM alias normally reruns the queries that created it, unless the alias was created as static. Full details are in the cy.get() API.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

cy.contains(content)

cy.contains() accepts a string, number, or regular expression and yields at most one element. A string matches a substring, so cy.contains('Save') can match “Save draft.” To require an exact text match, use an anchored regular expression:

cy.contains('button', 'Save').click()
cy.contains('button', /^Save$/).click()

When you omit the element selector, Cypress may yield a preferred interactive ancestor, such as a button or link, instead of the deepest matching descendant. Include a selector when the element type matters. For duplicate text, scope the query to its container.

cy.contains('tr', 'Jane').contains('button', 'Edit').click()

That chain first identifies the row by its text, then looks for its Edit button. See the cy.contains() API for supported arguments and options.

Scope selectors to the right container

A plain cy.get() generally starts again at the Cypress root rather than searching within the previous subject. Use .find() for descendants of the current subject, or .within() when several Cypress queries should run inside one container.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use .find() for a descendant query

cy.get('[data-cy="profile"]')
  .find('input')
  .should('have.length', 2)

Use .within() for a group of queries

cy.get('[data-cy="confirm-dialog"]').within(() => {
  cy.contains('button', 'Yes, Delete!').click()
})

Scoping is especially useful when a page has repeated text or controls: it makes the intended container part of the query instead of relying on a page-wide match.

Use accessible queries when semantics are the point

If the test should identify a control by the role and accessible name users receive, Cypress’s accessibility guidance demonstrates Cypress Testing Library queries:

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
cy.findByRole('button', { name: 'Submit' }).click()

Use this when role and accessible name are part of the behavior you intend to exercise. A test attribute serves a different purpose: it provides a dedicated hook without making visible wording the assertion. Both approaches can coexist in a suite. Read Cypress accessibility testing guidance for the documented integration.

Understand retries and assertions

Cypress retries queries while searching for matching elements and retries chained assertions until they pass or the applicable timeout expires. Prefer expressing the expected page state as a query plus an assertion:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
cy.get('[data-cy="saved-message"]').should('be.visible')

cy.contains() also accepts a timeout option and can be chained with assertions. For a transient message, an immediate not.exist assertion may pass before the message ever appears. If it matters that an action caused the message, first assert that it appears, then assert its later disappearance.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Know the query boundaries

  • Visibility: cy.contains() can find hidden elements. Add .should('be.visible') when visibility is the user-facing requirement.
  • Text matching: String content is a substring match. Use an anchored regular expression for exact wording, and account for whitespace in the rendered text.
  • Single result: cy.contains() yields at most one element, so use a different query when you need to assert on a set of matching elements.
  • Frames: cy.get() does not automatically search inside iframe documents. Follow Cypress’s separate iframe guidance when the target is inside a frame; see the cy.get() API.
  • Shadow DOM: cy.contains() has an includeShadowDom option. Unless overridden, its behavior follows Cypress configuration; check the setting and API behavior for applications that rely heavily on shadow roots.
  • Position selectors: Cypress demonstrates using .first() or .eq() rather than selector extensions such as :first or :eq(), making the intended operation clearer.

Generated selector priorities

Cypress.ElementSelector configures the attribute priority used by tools such as Cypress Studio and cy.prompt() when generating selectors. The documented default begins with data-cy, data-test, data-testid, and data-qa, followed by options including name, id, class, and tag. Cypress marks selectorPriority as under active development, so check the Cypress.ElementSelector API before relying on exact behavior in configuration.

Troubleshoot selector failures

  • The query finds no element: Check that the application reached the expected state, the selector matches the rendered markup, and the target is not inside an iframe. For repeated controls, confirm that the intended container is part of the query.
  • The wrong text match is returned: A string can match a substring, and Cypress may yield a preferred interactive ancestor. Add an element selector, use an anchored regular expression for exact text, or scope the query.
  • A hidden element matches: Add .should('be.visible') if the test requires a visible control.
  • A transient absence assertion passes too soon: Assert that the transient element appears after the action before checking that it disappears.
  • A selector breaks after a style or copy change: If the test is not meant to verify the style or wording, use a dedicated data-* testing attribute instead.
  • A shadow-root target is missed: Verify the Cypress configuration and the includeShadowDom option for cy.contains().

Or skip the browser setup

ScreenshotNeo takes a webpage screenshot through one API request; it does not replace Cypress selectors or assertions. Its clean-shot flow accepts cookie or consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, with page verdict and billing information in response headers. It also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for AI agents.

For a screenshot rather than a Cypress DOM query, make one GET request. See the ScreenshotNeo API documentation for request options.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo has 1,000 screenshots per month on its free plan with no card required; paid plans start at $5 for 3,000 screenshots. Sign up for the free plan.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.