dennis-w
dennis-w

Reputation: 2156

cypress selector on dom element attributes

I have two svg elements on my site:

<svg data-icon="times" ... > ...</svg>
<svg data-icon="sync" ... > ...</svg>

I like to select on of them based on their attribute data-icon. Something like this:

cy.get('svg').filter(?)

I Didn't find anything on the docu in the cy.get and cy.filter section. I know I could solve this by assigning classes or id around the elements or use the cy.each function to get one element, but for my tests this is a common problem and I am looking for the most comfortable solution.

Upvotes: 4

Views: 2715

Answers (1)

Gasoline and Sauce
Gasoline and Sauce

Reputation: 149

You can target the data attribute directly. Here's how the code would look like:

cy.get('[data-icon="times"]')

This would yield the element with a data-icon attribute of "times".

You could be even more specific by explicitly targeting only svg elements with that data attribute like so:

cy.get('svg[data-icon="times"]')

Here's the section of the docs for more reading.

Upvotes: 4

Related Questions