I have some classes which are dynamically generated in React. They always have the same prefix but they all end differently
How can I use Cypress to select a class name that begins with X?
<div class="this-is-always-the-same-abcd"></>
<div class="this-is-always-the-same-efgh"></>
<div class="this-is-always-the-same-ijkl"></>
To select an element by class you need to use . prefix and to select an element by its it, you should prefix id with # . The most common attribute you might find on your page would be a placeholder for an input or even a test-id where your selector starts and ends with square brackets.
Get Element By Containing Text in Cypress You can simply use the contains() function along with the tag name and should be able to get the element.
class selector selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class.
To everyone who really need to target class and cannot (Or do not want) use data-
attributes for some reasons. Solution is to use standard css selector.
cy.get('*[class^="this-is-always-the-same"]')
This will get all elements that has class starting with this-is-always-the-same
.
According to their Best Practices Documentation, you should use data-*
attributes to provide context to your selectors and insulate them from CSS or JS changes.
It's suggested that you follow these guidelines:
id
, class
, tag
.textContent
.data-*
attributes to make it easier to target elements.Instead, you should add a data-cy
attribute to target the selector that you're testing.
You can use this playground to determine an unique selector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With