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!!! 
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 share a prefix.
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"]')
Best for: Avoiding brittle selectors. This is a Cypress-recommended approach for long-term test stability.
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.