How can I use Cypress get class to select an element whose class name starts with a specific prefix?

Hey everyone!!

In my React app, some classes are dynamically generated and always begin with the same string but end differently. Example:

<div class="this-is-always-the-same-abcd"></div>
<div class="this-is-always-the-same-efgh"></div>
<div class="this-is-always-the-same-ijkl"></div>

What’s the best way to target these in Cypress?

Help me out guys!!! :raised_hands:

Hello automation engineers! Adding another highly effective strategy to the discussion initiated by @MattD_Burch about selecting elements with dynamic class names in Cypress.

This is the cleanest and most common way to match classes that start with a specific string.

cy.get('[class^="this-is-always-the-same"]')

Best for: Tailwind, CSS Modules, or styled-components where class names change per build but reliably share a prefix. This method uses the attribute starts-with selector, providing a robust way to target elements.

Hope this helps you streamline your tests with dynamic class names!

Hello @MattD_Burch, @vindhya.rddy and everyone who is a part of this discussion!!!

If possible, modify your component to include a custom attribute like data-testid or data-cy. Then select using that instead of the class name.

<div data-cy="my-dynamic-element"></div>
cy.get('[data-cy="my-dynamic-element"]')

This would be best to avoid brittle selectors. This is a Cypress-recommended approach for long-term test stability.

Hey everyone and especially the primary contributors @vindhya.rddy, @shilpa.chandel and @MattD_Burch!!!

If you can’t rely solely on the attribute selector or need extra control:

cy.get('div').filter((index, el) => {
  return el.className.startsWith('this-is-always-the-same');
}).should('have.length.at.least', 1)

Best for: More complex or nested elements where class might not be the only filter you need.