When using Cypress for automated testing, handling multiple elements with the same name is a common scenario. For example, if a page contains multiple buttons labeled "submit", it is important to pay special attention to precisely locating these elements.
Using the eq function
Cypress provides an eq function to select a specific element from a group. For instance, if there are five buttons named "submit" on the page, and you want to click the third button, you can write:
javascriptcy.get('button').contains('submit').eq(2).click();
Here, .eq(2) selects the third element (since indexing starts from 0).
Using first and last functions
If you only need to interact with the first or last element that has the same name, you can use first or last functions.
javascript// Click the first "submit" button cy.get('button').contains('submit').first().click(); // Click the last "submit" button cy.get('button').contains('submit').last().click();
Combining with parent elements
If elements with the same name are located in different sections of the page, you can first locate their parent elements and then select them. This allows for more precise control over element selection.
javascript// Assuming the second "submit" button is within a form with a specific ID cy.get('#formId2').find('button').contains('submit').click();
Using filter function
When elements have multiple identical sibling elements, the filter function can be used to filter out elements that meet specific conditions.
javascript// Select all "submit" buttons with a specific class name cy.get('button').contains('submit').filter('.specific-class').click();
Example Scenario
Suppose you have a webpage with multiple submit buttons for comments, each comment section having a "submit" button. If you want to click the submit button under a specific user's comment, you can write:
javascriptcy.get('.comment-section').contains('username').parent().find('button').contains('submit').click();
Here, .comment-section is the container for each comment, contains('username') locates the specific user's comment, and parent() and find() are used together to locate and click the correct "submit" button.
These are common methods and strategies for handling elements with the same name when using Cypress. I hope this helps with your project!