ScreenshotNeo

BlogHow-to

How to Select List Elements by Condition in Cypress

Use Cypress `.filter()` for conditional list selection, `.contains()` for a single text match, and `.not()` to exclude matches. Includes runnable examples and fixes for common selector issues.

By the ScreenshotNeo team30 September 202610 min read

How to Select List Elements by Condition in Cypress

To select list elements by condition in Cypress, start with a stable query such as cy.get('[data-cy="todo-item"]'), then narrow the yielded elements with .filter(). Use a CSS selector for classes or attributes, :contains() when several elements may match text, and .not() to exclude matches. Use cy.contains(selector, text) when you expect one matching element. These queries retry with Cypress’s normal timeout behavior, so avoid saving a DOM element and reusing it after the application re-renders.

1. Start with a stable list query

A conditional selection has two parts: query a collection and apply a condition to that collection. The collection should identify the right kind of item without depending on layout or styling. A dedicated test attribute is usually a good choice:

<ul>
  <li data-cy="todo-item" data-status="ready">
    <span>Pay electric bill</span>
    <button>Open</button>
  </li>
  <li data-cy="todo-item" data-status="waiting" class="disabled">
    <span>Book appointment</span>
    <button>Open</button>
  </li>
</ul>
cy.get('[data-cy="todo-item"]')
  .filter('[data-status="ready"]')
  .should('have.length', 1)
  .should('contain', 'Pay electric bill')

cy.get() accepts CSS selectors and yields the matching DOM elements. Cypress recommends dedicated data-* attributes because a style or copy change is less likely to break them than a selector tied to a class used for presentation. Cypress: cy.get().

Use data-cy, data-testid, or the convention already used by your test suite. Avoid reaching into a list by a long chain of structural selectors if the application can expose a stable test attribute. A selector such as ul > li:nth-child(3) identifies a position, not the meaning of an item, and may silently point to a different item when the list changes.

2. Filter a collection by CSS condition

.filter(selector) narrows the current collection to elements matching a selector. It must follow a command that yields DOM elements, such as cy.get() or .find(). The selector can express a class, attribute, or structural condition:

Query a stable list, then filter the yielded elements by the condition the test cares about.
Query a stable list, then filter the yielded elements by the condition the test cares about.
// Match an active class
cy.get('[data-cy="todo-item"]')
  .filter('.active')
  .should('have.length', 1)
  .click()

// Match an attribute value
cy.get('[data-cy="todo-item"]')
  .filter('[data-status="ready"]')
  .should('be.visible')

// Match elements that are not disabled
cy.get('tr')
  .filter(':not(.disabled)')
  .should('have.length.greaterThan', 0)

The filter is applied to the elements already in the collection. For example, cy.get('li').filter('.active') means “find list items, then keep those that are active.” It does not search every element on the page for an active class.

Cypress documents that .filter() yields the matching DOM element or elements, and it is safe to chain from that result. Queries and their chained assertions retry until they pass or time out. Cypress: cy.filter().

3. Select by text

One expected match: use cy.contains()

When the test expects one element with a given label, cy.contains(selector, text) is direct and readable:

cy.contains('li', 'Pay electric bill')
  .should('be.visible')
  .click()

Passing 'li' limits the candidates to list items. The text argument can be a string, number, or regular expression. To ignore letter case, pass the matchCase option:

cy.contains('li', 'pay electric bill', { matchCase: false })
  .should('be.visible')

.contains() yields at most one element. That makes it a useful choice for a unique label, but not for asserting that every item containing a substring was found. If the same words occur in more than one row, use a collection query and filter it instead. Cypress: cy.contains().

Several possible matches: filter the collection

For multiple list items containing a substring, use the jQuery :contains() selector through .filter():

cy.get('li')
  .filter(':contains("Services")')
  .should('have.length', 2)

This is a case-sensitive substring match. For example, it can match both “Services” and “Advanced Services.” If case-insensitive matching or more complex text normalization is needed, use a predicate assertion (shown below) or select by a stable attribute instead.

Text can contain non-breaking spaces, which look like ordinary spaces but are a different character. Cypress documents using the Unicode escape \u00a0 in the selector when that is the text in the page:

cy.get('li').filter(':contains("Advanced\u00a0Services")')

Cypress filter selector examples.

4. Exclude items that meet a condition

Use .not() to remove matching elements from a collection. This is useful for excluding archived text or selecting only enabled rows:

cy.get('li')
  .not(':contains("Archived")')
  .should('have.length.greaterThan', 0)

cy.get('tr')
  .filter(':not(.disabled)')
  .should('be.visible')

Use .not(':contains("...")') when the exclusion is based on text. cy.contains() is designed to find a match and yields at most one element; it has no direct negation mode for a whole collection. Cypress: cy.not().

Be precise about what is excluded. The first example excludes list items whose text contains the case-sensitive substring “Archived”; it does not exclude only an exact text match.

5. Check a JavaScript property or custom condition

CSS selectors work well for attributes and classes. If the condition depends on a DOM property or needs custom logic, make an assertion over the yielded collection. A .should(callback) callback is retried until its assertions stop throwing:

cy.get('[data-cy="item"]').should(($items) => {
  const readyItems = $items.filter((_, element) => {
    return element.dataset.status === 'ready'
  })

  expect(readyItems).to.have.length(1)
})

Keep Cypress commands out of the callback. Cypress may invoke it repeatedly while retrying; a Cypress command inside can be run multiple times and Cypress explicitly disallows that pattern. Use the callback to inspect the current yielded elements and make assertions, not to start another Cypress chain. Cypress: cy.should().

If you need to interact with the one element identified by custom logic, consider whether the same condition can be represented by an application attribute and expressed with .filter(). That produces a normal query chain that Cypress can retry as the page changes.

6. Use position only after narrowing the collection

When position is genuinely the condition, .first() and .eq(index) make the intent clear. Prefer applying them after a meaningful filter:

cy.get('li')
  .filter('.result')
  .eq(1)
  .click()

cy.get('ul')
  .find('li')
  .first()
  .should('contain', 'Home')

.eq(1) selects the second element because indexes start at zero. If order is part of the behavior under test, assert the count or relevant labels too; otherwise a reordered list can make a positional test pass against the wrong item. Cypress: cy.eq() and Cypress: cy.first().

7. Click the matching item safely

For a row whose label matches a condition, first decide whether the click target is the row or a control inside it. If clicking the row is the behavior, select that row and click it. If a button inside the row performs the action, find and click the button:

cy.get('[data-cy="todo-item"]')
  .filter(':contains("Pay electric bill")')
  .find('button')
  .click()

For a unique label, this is often simpler:

cy.contains('[data-cy="todo-item"]', 'Pay electric bill')
  .find('button')
  .click()

Assert the expected number of matches when duplicates would be a test failure. This prevents a selector from quietly targeting an unexpected row. Avoid adding .first() simply to silence multiple matches unless “the first matching row” is the behavior you mean to test.

8. Handle rerenders and detached elements

Modern applications often replace list nodes after a click, request, or state update. A Cypress chain that continues using a previously yielded element can then fail because that subject is detached from the document. Start a fresh query after an action that can rerender the list:

After an action triggers a rerender, query the current list again before asserting its state.
After an action triggers a rerender, query the current list again before asserting its state.
cy.get('[data-cy="result"]')
  .filter('.ready')
  .click()

// Query the current DOM again after the application updates
cy.get('[data-cy="result"]')
  .filter('.ready')
  .should('have.length', 0)

Assertions are automatically retried until they pass or time out, but retrying does not make an old DOM subject safe after the application replaces it. Build a new query from the page after the action. If the app updates asynchronously, assert the resulting state instead of inserting a fixed delay. Cypress retry-ability.

9. Choose the right pattern

Need Pattern What it yields
Class or attribute condition cy.get(...).filter('.active') All matching elements in the current collection
One text match cy.contains('li', 'Label') At most one element
Several text matches cy.get('li').filter(':contains("Label")') Every matching list item
Exclude text or selector matches cy.get('li').not(...) Collection with those matches removed
Custom DOM property .should(($items) => { ... }) Assertion over the current collection
Position within a meaningful subset .filter(...).eq(1) The element at the requested index

Use the expected match count, condition type, and rerender behavior to choose. A stable attribute plus .filter() is usually easiest to maintain for state such as status or category. Text selection is appropriate when the user-visible label itself is what the test needs to verify.

10. Troubleshooting

Symptom Likely cause Fix
.filter() reports it is not a function or has an invalid subject The prior command did not yield DOM elements. Start with cy.get(), .find(), or another DOM query, then chain .filter().
No elements match The selector is wrong, the list has not rendered yet, or the text differs in case or spacing. Inspect the actual DOM, assert against a stable test attribute, and remember :contains() is case-sensitive. Handle non-breaking spaces with \u00a0.
Only one of several text matches is returned cy.contains() yields at most one element. Use cy.get('li').filter(':contains("...")') and assert the expected collection length.
Test times out despite an element appearing briefly The element may be replaced by a rerender before a later chained command uses it. Break after the action and query the current DOM again.
“Detached from the DOM” error A yielded node was removed or replaced after the app updated. Use a fresh cy.get() chain after the state change and assert the new state.
Assertion callback produces a Cypress command error A Cypress command was called inside a retried .should(callback). Keep the callback synchronous and limited to inspecting its subject and making assertions.
Click targets the wrong matching item Text is duplicated, the selector is too broad, or position was added without intent. Scope to the correct list, include a stable attribute, and assert the count before clicking.

11. Reliability, runtime, and test cost

Conditional selection itself is local DOM work; the important reliability costs usually come from selector fragility and the page’s update timing. Dedicated test attributes reduce coupling to CSS. Querying a collection and filtering it keeps the condition legible, while assertions give Cypress a state to retry rather than relying on a guessed wait.

Keep collections scoped to the relevant list when a page has many similar elements. This makes the selector easier to reason about and avoids accidental matches elsewhere. Assert a length when duplicates or missing items indicate a defect. Re-query after actions that trigger a list replacement. These choices make a test less dependent on incidental page structure without adding fixed delays.

No numeric speed claim follows from these selector patterns. If a suite is slow, first look at page loading, app requests, and unnecessary waits. Avoid weakening assertions or selecting arbitrary positions to make a flaky test pass: those changes can hide the underlying state or selector problem.

12. FAQ

Can I use .filter() with a callback?

For a jQuery-style predicate on the yielded collection, a callback can be passed to .filter(). For assertions that Cypress should retry, use .should(callback) and keep Cypress commands out of it.

How do I match exact text?

:contains() checks for a case-sensitive substring. For a unique exact user-facing label, cy.contains() is convenient, but it also searches by contained text. If exact string equality is essential, inspect each candidate’s text in a retried assertion and compare its normalized value explicitly.

Can I select a list item by its child text?

Yes. Use cy.contains('li', 'Label') for a unique match, or filter the list item collection with :contains() when multiple matches are valid.

Or skip the browser setup

If the job is to capture a page screenshot while checking its rendered output, ScreenshotNeo provides a website screenshot API and MCP server. The one-call request below returns an image for the supplied URL. See the API documentation for request options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
  • Cookie banners, newsletter popups, and chat widgets are removed before capture; each cleanup step can be turned off.
  • Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Response headers identify the page verdict and billing status.
  • An MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf.
  • The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up free for 1,000 screenshots a month, no card required.