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 community!

@MattD_Burch your challenge with using Cypress to select elements with dynamic class names is a very common one, especially in modern React projects where CSS Modules or Tailwind introduce unpredictable class endings. I’ve certainly dealt with this exact situation myself!

What worked great for me was using the attribute starts-with selector. With Cypress, you can do something elegant like this:

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

That command precisely grabs all elements where the class attribute starts with the specific prefix you provide. It’s a beautifully clean way to use Cypress get class for dynamic class names without needing an exact match. Just make absolutely sure none of your other, unrelated classes start with the very same string, or you’ll inadvertently end up grabbing more elements than you intended.

Hope this helps you reliably target your elements!