'Cypress :: How to click on an image by selecting its alt value?
I need to select an image which is inside of a button. The problem is that there are six similar images and they do not have any unique identifier, except their alt message and source. Here is the code I am working with.
<div class="dropup-content" style="height: auto; max-height: 1000px;">
<button type="button">
<img src="images/en_US.png" alt="English" style="width: 45px; height: 30px;">
</button>
<button type="button">
<img src="images/nb_NO.png" alt="Norwegian" style="width: 45px; height: 30px;">
</button>
<button type="button">
<img src="images/fi_FI.png" alt="Finnish" style="width: 45px; height: 30px;">
</button>
<button type="button">
<img src="images/fr_FR.png" alt="French" style="width: 45px; height: 30px;">
</button>
<button type="button">
<img src="images/nl_BE.png" alt="Dutch" style="width: 45px; height: 30px;">
</button>
<button type="button">
<img src="images/de_DE.png" alt="German" style="width: 45px; height: 30px;">
</button>
</div>
Now, if I need to select the button with the alt value Swedish
, how would I do it? For example, I can get the first one using this code:
cy.get('.dropup-content').first().click()
However, the problem is that the sequence comes randomly every time. So I can not rely on the first()
or next()
methods. Is there any way in Cypress to click on the button with image attribute Swedish
?
Solution 1:[1]
You can do this like:
cy.get('[alt="Swedish"]').click()
Solution 2:[2]
Try
cy.get('button[alt="Swedish"]').click()
But if you have a control on how those buttons are created, I'd suggest you should add data-cy
tag to them and then access them by
cy.get('button[data-cy="Swedish"]').click()
Read why in best practices docu
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 | Mr. J. |
Solution 2 | DurkoMatko |