How to get the number of elements with Cypress

Recently, when working with Cypress again, I’ve met the issue that I cannot get the number of elements with Cypress. If the element is not found, Cypress will fail the test, which is not the result. In this blog, let’s see how you can do it with Cypress.

Donald Le
2 min readAug 5, 2023
Photo by Alice Triquet on Unsplash

Usually, if you have experience working with Selenium, you might think the below code is the one that gives you the number of elements for the given locator.

const numberOfElements = cy.get('css-locator').its('length');

But no, this line of code does not work as expected. There are two problems with this code:

  • Cypress is asynchronous, which makes it return the value right away before actually executing it -> the value of the number of elements will be `chainable<number>`, not the number
  • After Cypress finishes evaluating, it will execute the code. This time it will throw the timeout error if the element does not exist.

So how do you go through this problem?

First, you need to make sure you have a parent element that must exist, then find your elements in it using a then block.



Donald Le

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.