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. attributeFilterorder does not matter.- HTML attributes like
classoriddon't need square brackets. They can use the usual CSS/JS shorthand of.classand#id. There is a big difference between the square brackets and shorthand behavior. This will be addressed in a different note. - The HTML
elementtype also doesn't use square brackets.- However, it can't be appended to an
attributeFilterthat does't use square brackets (likeclassorid) because theelementtype would be interpreted as part of theattributeFilterstring.
- However, it can't be appended to an
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");