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 attributeFilter
s.
Here are the basic rules:
- It matches elements that match every
attributeFilter
. attributeFilter
order does not matter.- HTML attributes like
class
orid
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 (likeclass
orid
) because theelement
type would be interpreted as part of theattributeFilter
string.
- 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");