Locator Strategy in Cypress: CSS Cheat Sheet

Anshita Bhasin
3 min readMay 25, 2023

Locators play an important role in identifying and interacting with elements within web pages and user interfaces during test execution. To simplify this process, CSS Selectors offers a remarkable solution.

With CSS syntax, you can effortlessly select elements by targeting attributes such as tag name, class, ID, or attribute-value pairs.

Sharing the CSS Cheat Sheet for Cypress.io to help you effortlessly locate and interact with elements during your test automation

📌 ID: Quickly locate elements by their unique identifier

In case of fixed Id in DOM, use #IdValue

Example : cy.get(‘#logo’)

📌 Class Name: Target elements based on their class name

In the case of class in DOM, use .class

Example : cy.get(‘.input-group’)

📌 Tag Name: Select elements using their HTML tag name

In the case of an HTML tag , use [attributeName=attributeValue]

Example : cy.get(‘[onclick=”cart.add(‘43’);”]’)

📌 Multiple Classes: Select elements using their class names

In case of multiple classes in DOM, use .class1.class2.class3

Example : cy.get(‘.product-layout.col-lg-3.col-md-3.col-sm-6.col-xs-12’).first()

📌 Nth Value: Select elements using the operator “>”

To traverse to a specific DOM element, use >

Example : cy.get(‘div>button>i.fa.fa-shopping-cart’).first()

📌 Fixed Start Value: Select elements using operator ^

When the starting text is fixed, use the operator ^

Example : cy.get(‘[onclick^=”cart.add”]’)

📌 Fixed End Value: Select elements using the operator $

When the ending text is fixed, use the operator $

Example : cy.get(‘[onclick$=”.add(‘43’);”]’)

Conclusion

Cypress provides a powerful set of querying functions that you can use in combination with CSS selectors to locate elements. These functions include cy.get(), cy.contains(), and more.

While following Cypress's best practices, using data-* attributes to provide context to your selectors and keep them isolated from CSS or JavaScript changes is recommended. However, in cases where data-* attributes are not available or suitable, and you still want to utilize CSS, you can take advantage of the upcoming CSS locator strategy.

By effectively understanding and utilizing CSS selectors, you can enhance the precision and stability of your element targeting in Cypress tests.

Thanks for reading. Happy Learning! AB

For a more detailed understanding of the CSS locators strategy in Cypress, please refer to the video link provided below.

Video: https://youtu.be/z9btR_KSraY

Pdf: https://github.com/Anshita-Bhasin/Cypress-CSS-Cheat-Sheet/blob/main/CSS_Cypress_Cheat_Sheetpdf.pdf

Thanks for reading. Happy Learning! — AB

Thanks, Naveen AutomationLabs for the guidance and motivation.

Anshita Bhasin
Sr. Automation Engineer

GitHub | LinkedIn | Twitter | Youtube

--

--

Anshita Bhasin

QA Chapter Lead at Proptech company in Dubai.. Here to share and learn new things! Youtube => ABAutomationHub