When dealing with dynamic selectors, Cypress provides several methods to retrieve elements. Dynamic selectors typically refer to elements whose class names, IDs, or other attributes may change after page load or user interaction. Below are some methods for handling dynamic selectors and locating elements:
1. Elements with Static Text Content
If the element's text content is static and unique, you can use the contains command to locate the element:
javascriptcy.contains('fixed text content');
2. Using Fixed Attributes
If certain attributes of the element are fixed, you can directly locate the element using these attributes:
javascriptcy.get('[data-cy="fixed attribute"]');
3. Regex Matching for Attributes
If attribute values follow a specific pattern, you can use regex to match these attributes:
javascriptcy.get('input[name^="input-name-prefix-"]'); cy.get('div[class*="partial-class-name"]');
4. Using Parent or Sibling Element Relationships
Sometimes, you can locate dynamic elements by finding parent or sibling elements with stable selectors:
javascriptcy.get('#parent-element-id').find('.child-element-class'); cy.get('.sibling-element-class').next('.target-element');
5. Using .invoke() and jQuery Methods
For complex selection requirements, you can use the .invoke() function combined with jQuery methods:
javascriptcy.get('.dynamic-element').invoke('attr', 'name').then((name) => { // Further logic based on name });
6. Using Callback Functions for Filtering
You can use the .filter() method and pass a callback function to further filter matching elements:
javascriptcy.get('.list-item').filter((index, element) => { return element.textContent.includes('fixed text'); });
Practical Examples
Assume there is a to-do list where each item's ID is dynamically generated when a new to-do is added. You can use a static class name and the contains method with the to-do item text content to retrieve the specific to-do element:
javascriptcy.get('.todo-list-item').contains('Buy groceries');
Alternatively, if each to-do item has a data-test-id attribute starting with a specific format, such as todo- followed by a number, you can use regex to locate the element:
javascriptcy.get('[data-test-id^="todo-"]');
Overall, the best practice is to use fixed attributes as much as possible for locating elements, such as data-* attributes, which are specifically designed for testing and are unlikely to change with application updates.