乐闻世界logo
搜索文章和话题

How can I find classname an element with multiple classes in cypress

1个答案

1

In Cypress, to find elements with multiple classes, you can combine class names in your selector. Cypress uses selectors similar to jQuery. Suppose you need to find elements with class names btn, primary, and active; you can use the following method:

javascript
cy.get('.btn.primary.active')

The .get() method accepts a selector string that includes all matching class names, each prefixed with a dot (.).

Example

Suppose we have the following HTML structure:

html
<button class="btn primary active">Click me</button>

To locate this button in Cypress, you can use the following:

javascript
// Using all relevant class names cy.get('.btn.primary.active').click();

This will find the button with btn, primary, and active classes and perform a click action.

Notes

  • Avoid unnecessary spaces in the selector, except when used for descendant selectors.
  • The order of class names is irrelevant to the selector; both .btn.primary.active and .active.primary.btn function identically.
  • If a class name is not unique, the selector matches all elements. To refine the selection, incorporate additional attributes or contextual details.

When selecting elements in Cypress, it is recommended to use specific and unique selectors to improve test accuracy and efficiency.

2024年6月29日 12:07 回复

你的答案