cypress get element by attribute

Cypress Get Element By Attribute

Have you ever tried to locate an element on a webpage using its attribute value? It can be quite a challenge, especially if you are not familiar with the different methods available to you. Fortunately, Cypress provides several ways to get elements by attribute.

Using the get() Method

The simplest way to get an element by attribute in Cypress is by using the get() method. With this method, you can locate an element by its attribute value or even a combination of attributes.

cy.get('[data-test-id="my-element"]');
cy.get('[data-test-id="my-element"][data-state="active"]');

As you can see in the examples above, we can use the attribute selector syntax to specify the attribute name and value. You can also chain multiple attributes together to create a more specific selector.

Using the find() Method

If you need to locate an element that is nested inside another element, you can use the find() method in combination with the attribute selector. This method will search for the element within the context of the selected element.

cy.get('.parent-element').find('[data-test-id="my-element"]');

In this example, we first select the parent element using its class name and then search for the nested element using its attribute value.

Using the contains() Method

If you need to locate an element based on its text content and attribute value, you can use the contains() method along with the attribute selector. This method will search for the text content within the selected element and its descendants.

cy.contains('[data-test-id="my-element"]', 'Button');

In this example, we search for an element that has the attribute value of data-test-id="my-element" and contains the text content of Button.

Using Custom Commands

If you find yourself using the same selector repeatedly, you can create a custom command to simplify your code. For example, you could create a command called getByTestId() that searches for elements with the attribute value of data-test-id.

Cypress.Commands.add('getByTestId', (id) => {
  return cy.get(`[data-test-id="${id}"]`);
});

You can then use this command throughout your tests:

cy.getByTestId('my-element');

As you can see, there are several ways to get an element by attribute in Cypress. Whether you prefer using the built-in methods or creating custom commands, you can easily locate the elements you need for your tests.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe