'cypress - how to get classes of element

I want to return class names of DOM element as string or (preferable) array of strings.

cy.get(selector).?

I don't want to use

cy.get(selector).should('have.class', 'abc')

as I need to use the class name further in the test.



Solution 1:[1]

You'll use the .invoke() to call the .attr() to get the classList of the jquery element.

// html
<ul class="class1 class2 class3"> List
</ul>
cy.get(selector)
  .invoke('attr', 'class') // returns "class1 class2 class3"
  .then(classList => classList.split(' ')) // converts to array of strings

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jjhelguero