App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Get Started free
Home Guide CSS Selectors in Cypress

CSS Selectors in Cypress

By Antra Verma, Community Contributor -

More often it is required to test the behavior of certain elements on the web application. Selectors help to identify those elements while writing the tests. In Cypress, CSS selectors are the only locators available. However, it can also work with XPath, with the help of an additional plugin. This guide will discuss different CSS selectors and how to use them with the Cypress framework.

What are CSS selectors?

CSS selectors are the pattern used to identify elements on a web page based on their style. 

There are a number of selectors available in CSS given as below:

1. Basic CSS Selectors

Selector NameDescriptionExample in Cypress
ID SelectorCSS ID Selector is an attribute that is passed to an HTML element. One can use the # symbol along with the value of the ID attribute to get the element.
cy.get(‘#login-btn’)

Matches the element that has the same id as ‘login-btn’.

Class SelectorClass is another attribute of an HTML element that can be used to identify the element using dot (.) with the value of the class attribute.
cy.get(‘.email’)

Matches the elements that have the same class as ‘email’.

Type SelectorOne can also use the tag name or type of the HTML element to select it from the page.
cy.get(‘span’)

Matches the ‘span’ elements from the given page.

2. CSS Attribute Selectors

Selector NameDescriptionExample in Cypress
Has Attribute SelectorThe HAS selector just checks to see if an element has the specified attribute.
cy.get(‘[data-active]’)

Matches the element that has the attribute ‘data-active’ set.

Exact Attribute SelectorThis selector will only match elements that have the specified attribute with the exact specified value. 
cy.get(‘[data-active=”true”]’)

Matches the element that has the attribute ‘data-active’ set to true.

Begins with SelectorIf one wants to check for an attribute that starts with a specific value then the begins with attribute selector is helpful.
cy.get(‘[data-color^=”r”]’)

Matches the element that has the attribute ‘data-color’ that begins with the letter ‘R’.

Ends with SelectorThis selector is identical to the begins with attribute selector but checks the end of the value instead.
cy.get(‘[data-color$=”r”]’)

Matches the element that has the attribute ‘data-color’ that ends with the letter ‘r’.

Substring Attribute SelectorThis is similar to the last two selectors, but it checks that the string passed to it appears anywhere in the attribute value.
cy.get(‘[data-color*=”e”]’)

Matches the element that has the attribute ‘data-color’ in which the letter ‘e’ appears. 

3. Combination Selectors

Selector NameDescriptionExample in Cypress
Descendant  SelectorThis selector allows one to select any element that matches a specific selector which is a descendant of an element that matches a different selector.
cy.get(‘.container p’)

Matches all the p tags that come under the element with the class name ‘container’.

CSS Child SelectorCSS child selector allows you to select only the direct child element of an HTML element.
cy.get(‘.container > p’)

Matches all the p tags that come directly under the element with the class name ‘container’.

General Sibling SelectorThis selector allows you to select sibling elements that come after an HTML element.
cy.get(‘.box ~ p’)

Matches all the p tags that come after the element with the class name box.

Adjacent Sibling SelectorIt is similar to the general sibling selector but can only select the siblings that come directly after the element.
cy.get(‘.box + p’)

Matches the p tag that comes directly after the element with the class name box.

Or SelectorThis selector allows you to select elements that match at least one of the selectors.
cy.get(‘.square, #rect’)

Matches the elements that have either class name ‘square’ or id attribute equal to ‘rect’.

And SelectorThis selector allows one to select elements that match all the selectors specified.
cy.get(‘div.black’)

Matches the div that has a class name equal to black.

Note: Here is the complete list of all the CSS Selectors available

How to use CSS Selectors in Cypress?

Step 1 Setup project with Cypress 

To set up a new project in Cypress follow the below steps

  • Initialize a new project
npm init -y
  • Install Cypress 
npm i cypress
  • Verify Cypress installation
npx cypress verify
  • Run Cypress
npx cypress open

Step 2 Configure Cypress

  • A new window like below will be opened, Click ‘E2E Testing’ to configure it.

Welcome to Cypress

  • New files related to Cypress will be configured for the project. Click ‘Continue’.

New files related to Cypress

  • Select a browser to run tests.

Choose a Browser

  •  Click ‘Create new empty spec’

Create new empty spec

  •  Choose a path for the spec file and click ‘Create Spec’

Create Spec 1

  • Run the spec file by clicking on ‘Okay, run the spec’

Okay run the spec

  • You shall see the default test being passed on the browser.

default test being passed on the browser

Let’s write a test to see if a user can log in to https://bstackdemo.com/ 

describe("CSS selectors in Cypress Tutorial", () => {
it("Login with Demo User", () => {
cy.visit("https://bstackdemo.com/signin");

cy.get("#react-select-2-input")
.type("demouser", { force: true })
.type("{enter}");

cy.get("#react-select-3-input")
.type("testingisfun99", { force: true })
.type("{enter}");

cy.get('#login-btn').click();
});
});

Save the file. Cypress will automatically run the test.

Cypress will automatically run the test

How to Check CSS style using Cypress

Let’s write another test in which we test the application that changes a CSS variable using Cypress Check CSS Style.

The demo application only contains an input element of type=”color” as shown below. 

Demo application

When one chooses a color, the background color of the web page changes with that color.

the background color of the web page

Let’s write a test to check the same using Cypress Check CSS style.

describe("Check CSS style", () => {
it("changes background color", () => {
cy.visit("http://127.0.0.1:5500/index.html");

cy.get("#color-picker")
.invoke("val", "#33BEFF")
.trigger("change");

cy.get("body")
.should("have.css", "background-color", "rgb(51, 190, 255)");
});
});

In the above snippet, we visit the URL where the application is running and select the input element using its ID selector. Then the invoke() method passes the value of test color “#33BEFF” to the input element and the trigger() method triggers the change event.

The should() method checks if the background color of the body element is actually changed on the page. 

Run the test and see the result.

Test Result

It is highly important to perform these tests on real devices. BrowserStack allows you to execute your Cypress test files on multiple platforms and multiple browsers. 

The cloud platform of BrowserStack allows the testers to perform these tests under real-world conditions on multiple devices available at the same time.

Try BrowserStack now

Tags
Automation Testing Cypress

Featured Articles

Fixing Browser Compatibility Issues with CSS Opacity & RGBA

Dynamic Rendering using HTML and CSS

App & Browser Testing Made Easy

Seamlessly test across 20,000+ real devices with BrowserStack