Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 725
dennis-w Avatar asked Sep 16 '25 00:09

dennis-w


1 Answers

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.

like image 51
Gasoline and Sauce Avatar answered Sep 18 '25 13:09

Gasoline and Sauce