Open In App

Cypress Locators - How to find HTML elements

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Cypress is a powerful automation testing tool for web applications that allows you to easily manipulate the DOM (Document Object Model). To access any WebElement in the DOM (Document Object Model), use Cypress locators, which are similar to Selenium locators. You can interact with elements on a webpage by selecting them using various methods, like cy.get() and then performing actions such as clicking, typing, or asserting their state.

What is Cypress Locators?

In automation, a Locator is an object that identifies and retrieves elements on a webpage based on specific criteria. To automate tasks on these elements, you first need to find them using these locators and then perform actions. Locators can be of various types, such as id, CSS, XPath, and tag-based selectors.

Cypress supports multiple locator types like tags, ids, classes, attributes, and text. Although Cypress doesn't natively support XPath selectors, you can add this functionality by installing the cypress-xpath plugin. This plugin enables XPath-based element selection within the Cypress framework.

Get HTML Element by ID Selector in Cypress

The “id” attribute in HTML is used to uniquely identify an element within a web page. ID is used to find and interact with HTML element. Moreover, you can obtain an HTML element by an ID selector in Cypress with the command 'cy.get()' using the '#' symbol followed by the ID of the Element.

Syntax: cy.get('#elementId').click(); // Replace 'elementId' with the real ID of the element you want to select

Example of Get HTML Element by ID Selector in Cypress

Consider an HTML button element with the id submit_button and the class submit_button_class:

HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button id="submit_button" class="submit_button_class">Submit</button>
</body>
</html>

To select this HTML element by its id in Cypress, use the following command:

JavaScript
cy.get('#submit_button')

In this command, # is used as a prefix to denote the id inside cy.get().

Once you have located the HTML element, you can perform actions like clicking, as demonstrated in the example below:

JavaScript
cy.get('#submit_button').click();

In the above example, the button with the ID submit_button is clicked.

Get HTML element by Class in Cypress

In Cypress, to grab any HTML element by its class, one can simply run 'cy.get' with a '.' in front while providing the class name for said element.

Syntax: cy.get('.your_class_name')

For example, consider an HTML div element with the class name user_profile:

HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div class="user_profile">Profile</div>
</body>
</html>

To select this element by its class in Cypress and perform an action, you could use:

JavaScript
cy.get('.user_profile').click();

In this example, the div element with the class user_profile is clicked.

Get HTML element by Tag Name in Cypress

You can use it directly by specifying the tag name itself as an argument to 'cy.get()' in Cypress. To select an HTML element by its tag name in Cypress, use the following command:

Syntax: cy.get('tag_name')

For example, consider an HTML paragraph element:

HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>

To select this element by its tag name in Cypress and perform an action, you could use:

JavaScript
cy.get('p').should('contain', 'This is a paragraph.');

In this example, the paragraph element (<p>) is selected, and an assertion is made to check that it contains the specified text.

Get HTML element by Attribute in Cypress

In Cypress, you can select HTML elements using various attributes, including id, class, and other attributes like name. You can pass CSS selectors inside the cy.get() command to locate elements based on these attributes.

Consider an HTML form for a newsletter subscription with the following elements:

HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<form>
  <input id="subscriber_name" class="form-input" type="text" name="name" placeholder="Name">
  <input id="subscriber_email" class="form-input" type="email" name="email" placeholder="Email">
  <button id="subscribe_button" class="form-button" type="submit">Subscribe</button>
  <div class="notification error-message">Please enter a valid email address</div>
</form>

</body>
</html>

To interact with these elements in Cypress, you can use the following commands

1. Select the name input by its name attribute and type a name:

JavaScript
cy.get('input[name="name"]').type('John Doe');

2. Select the email input by its id attribute and type an email:

JavaScript
cy.get('input[id="subscriber_email"]').type('[email protected]');

3. Select the subscribe button by its id attribute and click it:

JavaScript
cy.get('#subscribe_button').click();

4. Assert that an error message is displayed if the email format is invalid:

JavaScript
cy.get('.notification.error-message').should('contain.text', 'Please enter a valid email address');

Here’s a complete example demonstrating these steps in a Cypress test:

JavaScript
describe('Newsletter Subscription Form', () => {
  it('Check Subscription Process', () => {
    cy.visit("https://www.example.com/subscribe");
    cy.get('input[name="name"]').type('John Doe');
    cy.get('input[id="subscriber_email"]').type('[email protected]');
    cy.get('#subscribe_button').click();
    cy.get('.notification.error-message').should('contain.text', 'Please enter a valid email address');
  });
});

In this test:

  • The name input is selected by its name attribute, and a name is typed into it.
  • The email input is selected by its id attribute, and an email address is typed into it.
  • The subscribe button is selected by its id attribute, and it is clicked.
  • An assertion is made to check if an error message is displayed using a CSS class selector.

These examples show how to use different attribute selectors to locate and interact with elements in Cypress.

Cypress CSS selectors with Regular Expression (RegEx) Patterns

Cypress supports CSS selectors with regular expression (RegEx) patterns to dynamically select elements based on specific criteria within their attributes. Here are some commonly used symbols and their descriptions:

  • *: Matches elements containing the specified value.
JavaScript
cy.get('[class*="button"]') // Matches all elements with a class containing "button"
  • $: Matches elements ending with the specified value.
JavaScript
cy.get('[class$="active"]') // Matches all elements with a class ending in "active"
  • ^: Matches elements starting with the specified value.
JavaScript
cy.get('[class^="header"]') // Matches all elements with a class starting with "header"

Working with Multiple Elements in Cypress

You can utilize the Cypress command, such as 'cy.get()' with different locators, to uniquely identity/target as many elements on a web page as you want. You can select several elements in Cypress and run actions against them, for example, 'each()', 'should()', 'invoke()', etc. Hence, you will be in a position to interact with and make assertions on several elements simultaneously . For example, if you want to interact with elements having the common class, then you use commands like 'each()' which iterate over them, doing something with each of them. For example :

JavaScript
cy.get('.commonClass').each(($element) 
{
    cy.wrap($element).click(); 

// Click on each element with the class 'commonClass' 

});

The small code snippet shall show how you can click on each element that has class 'commonClass'.

Useful Cypress Locator Functions

There are a number of useful locator functions within Cypress, all of which can be used to target elements on a web page more precisely. Some of the commonly used Cypress locator functions include :

cy.get() : This function is used for selecting elements on the page with respect to several locators like class, id, tag name, attribute etc.

find() : It finds child elements within a selected element.

eq() : It helps in selecting a single element from many elements based on its index position.

first() : Selects the first element from the group of matched elements based on the locator.

last() : Selects the last element based on the locator from the group of matched elements.

filter() : Filters elements based on some specified condition or criteria.

contains() : Selects elements containing a specific text.

within() : This will define a scope within which the selection will take place and will have the capability of looking for elements in a certain container.

Listing here are the locator functions that make things flexible and powerful while targeting any elements during test automation with Cypress.

Get the HTML Element by XPath in Cypress

In Cypress, XPath selectors are not natively supported out of the box. However, you can easily add XPath support by installing a third-party plugin called cypress-xpath. Here’s how you can do it and use XPath selectors in Cypress:

Installing cypress-xpath Plugin

1. Install the Plugin: First, install the cypress-xpath plugin using npm:

npm install -D cypress-xpath

2. Configure cypress/support/index.js: Open your Cypress configuration file (cypress/support/index.js) and add the following lines to enable the XPath commands:

JavaScript
import 'cypress-xpath';

3. Using XPath Selectors

Once you have installed and configured the cypress-xpath plugin, you can use XPath selectors in your Cypress tests.

Here’s an example:

JavaScript
describe('XPath Selector Example', () => {
  it('Check Element Using XPath', () => {
    cy.visit("https://www.example.com");
    cy.xpath('//input[@id="username"]').type('myusername');
    cy.xpath('//button[contains(text(), "Submit")]').click();
  });
});

Explanation

  • cy.visit(): Loads the webpage you want to test.
  • cy.xpath(): This command is made available by the cypress-xpath plugin and allows you to use XPath selectors directly.
  • XPath Syntax: XPath expressions like //input[@id="username"] select elements based on their attributes (id="username" in this case).
  • Actions and Assertions: You can perform actions (e.g., typing into an input field) and assertions (e.g., clicking a button) using XPath selectors.

Conclusion

Cypress Locator also provides a number of locator functions that you can use for finding HTML elements within a webpage based on different attributes, such as 'cy.get()', 'find()', 'eq()', 'first()', 'last()', 'filter()', 'contains()', 'within()'. You can also use XPath with 'cy.xpath()' in order to locate the elements on the basis of their path in a document structure. Together, this provides a very powerful means of targeting elements using expressions. These locator functions and XPath can be exploited in Cypress to locate HTML elements and interact with them, providing higher precision and robustness to your test scripts .


Next Article

Similar Reads