How to handle dynamic elements in cypress

Handling dynamic elements is an important aspect of Cypress automation testing. There are several ways to locate and interact with dynamic elements effectively. We can use CSS or XPath selectors with the get() method, utilizing patterns such as nth-child, starts-with, or ends-with to target elements dynamically.

Additionally, we can use the eq() method to access an element based on its index when multiple elements match a selector. The find() method can also be combined with eq() to locate a specific element within a parent. Another useful method is contains(), which helps identify elements based on their visible text — even when other attributes are dynamic.

Below are some example scripts demonstrating these approaches in Cypress.

🔹 1. Using get() with CSS Selectors

You can locate dynamic elements using CSS attributes such as nth-child, starts-with, or ends-with.

// Using nth-child to select the third item in a list
cy.get('.list-item:nth-child(3)').click();

// Using attribute selector to match elements whose id starts with "btn_"
cy.get('[id^="btn_"]').click();

// Using attribute selector to match elements whose id ends with "_submit"
cy.get('[id$="_submit"]').click();

Explanation:

^= → starts with
$= → ends with
*= → contains substring


🔹 2. Using eq() to Target by Index

When multiple elements share the same selector, eq() helps you pick one by its index (starting from 0).

// Click the second button among many with the same class
cy.get('.dynamic-button').eq(1).click();

// Get the third list item
cy.get('.list-item').eq(2).should('be.visible');

🔹 3. Using find() and eq() Together

You can first locate a parent element, then narrow down to a specific child element using find() and eq().

// Find a specific button inside a container
cy.get('.button-container')
.find('.dynamic-button')
.eq(2)
.click();

Explanation:
find() → Searches within a specific parent element.
eq() → Selects the nth element from the found list.

🔹 4. Using contains() for Text-based Dynamic Elements

When elements have dynamic IDs or classes but predictable text, contains() is very helpful.

// Click a button with specific visible text
cy.contains('button', 'Submit').click();

// Click a link that contains partial text
cy.contains('a', 'Learn More').should('have.attr', 'href');

Explanation:
contains() locates an element by its visible text content. You can specify the element type (like button, a, or div) for more precision.
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x