In Cypress you can get (query) elements by CSS and jQuery selectors. Watch the video Css And jQuery Selectors In Cypressopen in new window to see these examples in action.

Select by id

<div id="person">Joe</div>
cy.get('#person').should('have.text', 'Joe')
// cy.contains also lets you specify a selector
cy.contains('#person', 'Joe')

Combine selectors

You can combine selectors, for example to find all elements with class "person" AND class "student", list them together without spaces.

<div class="person">Joe</div>
<div class="person student">Mary</div>
cy.get('.person.student').should('have.text', 'Mary')

Combine class and attributes

You can select an element by combining ids, class names, attributes. For example, let's find all elements with class name "person" AND data attribute group equal to "a1":

<div class="person">Joe</div>
<div class="person student">Mary</div>
<div class="person student" data-group="a1">Ann</div>
  .should('have.text', 'Ann')
  .and('have.class', 'student')


Sometimes you want to find an element inside another element. In this case, separate the selectors using spaces. For example, to find the students somewhere inside the group "b2" we can use:

<ul data-group="a1">
  <li class="student">Joe</li>
<ul data-group="b2">
  <li class="student">Mary</li>
  <li class="student" data-rank="junior">Ann</li>
cy.get('[data-group="b2"] .student')
  .should('have.length', 2)
  // let's find all junior students
  // using
  .should('have.text', 'Ann')

jQuery selectors

jQuery selectors extend the CSS selectors with some powerful features. For example, to find visible elements, we can use :visible jQuery selector. Similarly, there is :hidden jQuery selector.

<ul class="university">
  <li class="student" style="display:none">Joe</li>
  <li class="student">Mary</li>
  <li class="student">Ann</li>
// select using hierarchy of classes
cy.get('.university .student').should('have.length', 3)
// select only the visible student elements
cy.get('.university .student:visible').should('have.length', 2)
// select only the hidden elements
cy.get('.university .student:hidden')
  .should('have.length', 1)
  .and('have.text', 'Joe')
  .and('have.css', 'display', 'none')