Locating Cypress Element by Class Prefix

Is there a way to locate an element in Cypress using get by a class name prefix?

1 Like

Hey there, To locate an element in Cypress using a class name prefix, you can employ the get command along with a CSS attribute selector. Specifically, you can utilize the attribute selector that targets elements with a class attribute starting with a specific prefix. Here’s how you can do it:


cy.get('[class^="prefix-"]')

If you’re looking to search within a specific element for elements with a class name prefix, you can use the find command in Cypress. This command allows you to narrow down your search scope. Here’s how you can do it:


cy.get('.parent-element').find('[class^="prefix-"]')

Another approach to locating elements with a class name prefix in Cypress is by utilizing the filter command along with a callback function. This method enables you to filter elements based on their class name prefix. Here’s how you can implement it:

cy.get('.element-list').filter((index, element) => {
    return Cypress.$(element).attr('class').startsWith('prefix-');
})