Open In App

How to get 2nd div of the same class with Cypress?

Last Updated : 15 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Cypress, interacting with elements of the same class often requires selecting specific instances, like targeting the second <div> with a particular class. This can be achieved by using Cypress’s .eq() command, which allows you to select an element at a specific index from a set of matched elements.

In this example, we will demonstrate how to get the second <div> with the same class using Cypress.

Example to get 2nd div of the same class with Cypress

HTML Code (Multiple Divs with the Same Class)

Here’s a simple example with three <div> elements that share the same class:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Div Selection Example</title>
</head>
<body>
    <div class="my-div">First Div</div>
    <div class="my-div">Second Div</div>
    <div class="my-div">Third Div</div>
</body>
</html>

Cypress Test Code

The following Cypress test selects the second <div> with the class my-div and verifies its content:

JavaScript
describe('Select the second div with the same class', () => {
  it('should get the second div with class "my-div"', () => {
    // Visit the page with the divs
    cy.visit('index.html');

    // Get all divs with the class "my-div" and select the second one (index 1)
    cy.get('div.my-div').eq(1) // Index starts at 0, so 1 is the second div
      .should('contain', 'Second Div'); // Verify the text of the second div
  });
});

Explanation

  • Visit the page: cy.visit('index.html') loads the page that contains the div elements.
  • Get all divs with the same class: cy.get('div.my-div') selects all the <div> elements with the class my-div.
  • Select the second div: .eq(1) is used to select the second <div> in the collection. Indexing in Cypress (and JavaScript) starts at 0, so .eq(1) corresponds to the second element.
  • Verification: should('contain', 'Second Div') verifies that the second <div> contains the text "Second Div".

Output

When you run this test, Cypress will:

  • Load the page with the multiple divs of the same class.
  • Select the second div (index 1) in the group.
  • Verify that the content of the second div is "Second Div".
output
Output

Conclusion

Using the .eq() command in Cypress is an effective way to target a specific element within a collection of elements sharing the same class. In this case, selecting the second <div> with the class my-div is straightforward and can be easily verified.


Next Article
Article Tags :

Similar Reads