Skip to content

Latest commit

 

History

History
62 lines (43 loc) · 2.07 KB

get-element-with-multiple-attributes.md

File metadata and controls

62 lines (43 loc) · 2.07 KB

Get element with multiple attributes

Usually when using the Cypress get() command, one attribute is enough to target an element, but it's possible to use more than one attribute too!

This is useful when targeting an element that's generated by a framework or library and can't receive a custom id or data- attribute.

Given these elements:

<!-- Select this -->
<div class="tab container rounded" tabindex="-1"></div>

<!-- DO NOT select these -->
<div class="tab container rounded" tabindex="0"></div>
<div class="container rounded" tabindex="-1"></div>

The first element can be selected like this:

cy.get('.tab[tabindex="-1"]');
// OR
cy.get('[tabindex="-1"].tab');

Cypress uses the jQuery multiple attribute selector documented here.

Here is the syntax:

cy.get("[attributeFilter1][attributeFilter2][attributeFilterN]");

🚨 Note: NO spaces are allowed between attributeFilters.

Here are the basic rules:

  • It matches elements that match every attributeFilter.
  • attributeFilter order does not matter.
  • HTML attributes like class or id don't need square brackets. They can use the usual CSS/JS shorthand of .class and #id. There is a big difference between the square brackets and shorthand behavior. This will be addressed in a different note.
  • The HTML element type also doesn't use square brackets.
    • However, it can't be appended to an attributeFilter that does't use square brackets (like class or id) because the element type would be interpreted as part of the attributeFilter string.

Here's an example:

<div class="tab container rounded" tabindex="-1"></div>
<span class="tab container rounded" tabindex="-1"></span>
// ✅ This works
cy.get("div.tab");

// ❌ This DOES NOT work because it's interpreted as `class="tabdiv"`
cy.get(".tabdiv");

References