XPath And CSS Selector Techniques

Advanced XPath And CSS Selector Techniques In Cypress

Share This Spread Love
Rate this post

Testing is essential to ensure software operates correctly, and automated testing is pivotal in confirming the reliability and stability of web applications. Cypress has become popular due to its simplicity and effectiveness in automated testing.

An essential aspect of automated testing is identifying elements on web pages for interaction. XPath and CSS selectors are powerful techniques for locating these elements. This article will delve into advanced XPath and CSS selector techniques in Cypress.

What is XPath?

XPath, which stands for XML Path Language, is a query language utilized for traversing and selecting nodes within an XML or HTML document. XPath finds extensive applications across different domains, including web development, data processing, and automation testing.

Following is an overview of how XPath functions and its application in web development and testing:

  • Node Selection: Uses a path-like syntax to select nodes (elements) within an HTML document.
  • Node Relationships: Can traverse the document tree using relationships like parent, child, ancestor, and descendant.
  • Attribute Selection: Selects nodes based on their attributes and attribute values.
  • Positional Selection: Selects nodes based on their position within the document tree.
  • Conditional Selection: Supports functions, operators, and conditions to select nodes based on criteria.

Cypress predominantly relies on CSS selectors for locating and interacting with web elements, it also offers support for XPath. XPath can serve as a robust alternative or supplement for element location, particularly when dealing with intricate or dynamic web structures.

XPath in Cypress

While Cypress generally favours CSS selectors for element locating, it does offer XPath expressions as an alternative locator option.

To utilize XPath locators in Cypress, you’ll need to install the cypress-xpath plugin. This plugin extends Cypress with XPath support, enabling the use of the cy.xpath() command to locate elements using XPath expressions.

This is how you can set up and use XPath in Cypress:

  1. Install the cypress-xpath plugin:
npm install -D cypress-xpath
  1. Import the plugin in your Cypress support file (e.g., cypress/support/e2e.js):
  1. Use the cy.xpath() command in your tests:

In the above examples, we’re utilizing XPath expressions to pinpoint specific elements within the web page. For instance, we’re locating a button element labelled “Submit” and performing a click action on it. Additionally, we’re identifying an input field characterized by the attribute type=”email” and entering text into it.

Following are some common XPath techniques you can use in Cypress:

  • Locating elements by tag name: cy.xpath(‘//div’)
  • Locating elements by attribute: cy.xpath(‘//input[@type=”text”]’)
  • Locating elements by text content: cy.xpath(‘//button[text()=”Submit”]’)
  • Locating elements by position: cy.xpath(‘//ul/li[2]’) (selects the second list item)
  • Combining predicates: cy.xpath(‘//div[@class=”example” and contains(text(), “Click me”)]’)

It’s important to note that using XPath locators in Cypress requires the additional cypress-xpath plugin, which may introduce potential compatibility issues or maintenance overhead. Therefore, it’s recommended to carefully evaluate the trade-offs and consider using XPath only when CSS selectors are not sufficient or practical for your use case.

What are CSS Selectors?

CSS selectors are patterns used to target and select HTML elements on a web page based on their attributes, relationships, or content. They allow you to apply styles, manipulate elements, or select them for other purposes, such as testing or scripting.

Selector Name Description Example in Cypress
Basic CSS Selectors
Type Selector Target elements based on their HTML tag name p (selects all <p> elements)
Class Selector Target elements based on their class attribute .highlight (selects all elements with the class “highlight”)
ID Selector Targets a unique element based on its ID attribute #main-content (selects the element with the ID “main-content”)
Universal Selector Targets all elements on the page * (selects all elements)
Attribute Selectors
Attribute Presence Selector Targets all elements on the page [disabled] (selects all disabled elements)
Attribute Value Selector Target elements with a specific attribute value [type=”text”] (selects all elements with the “type” attribute set to “text”)
Attribute Contains Selector Targets elements with an attribute value containing a specific string [class*=”nav”] (selects elements with a class attribute containing the string “nav”)
Attribute Starts With Selector Targets elements with an attribute value starting with a specific string [data-name^=”john”] (selects elements with a “data-name” attribute starting with “john”)
Attribute Ends With Selector Targets elements with an attribute value ending with a specific string [href$=”.pdf”] (selects elements with an “href” attribute ending with “.pdf”)
Descendant Combinator Targets elements that are descendants (children, grandchildren, etc.) of another element div p (selects all <p> elements inside <div> elements)
Child Combinator Target elements that are direct children of another element ul > li (selects all <li> elements that are direct children of <ul> elements)
Adjacent Sibling Combinator Target elements that are adjacent siblings of another element h1 + p (selects the <p> element immediately following an <h1> element)
General Sibling Combinator Target elements that are siblings of another element, regardless of their position div ~ p (selects all <p> elements that are siblings of <div> elements)
Pseudo-classes and Pseudo-elements
Pseudo-classes Target elements based on their state or position :hover (targets elements when hovers), :first-child (targets the first child element of its parent)
Pseudo-elements Target and style a part of an element ::before (inserts before an element’s content), ::after (inserts content after an element’s content)

How to use CSS Selectors in Cypress?

Following are the steps to use CSS selectors in Cypress:

Step 1: Set up a project with Cypress

  • Initialize a new project
  • Install Cypress
  • Verify the Cypress installation
  • Run Cypress
#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: Use CSS selectors in your tests

Cypress supports using CSS selectors to locate and interact with elements on a web page out of the box. To target specific elements, you can use the cy.get() command followed by a CSS selector.

// Locating elements by tag name
cy.get(‘button’)// Locating elements by class name

// Locating elements by ID

// Locating elements by attribute

// Combining selectors
cy.get(‘form input.email-field’)

// Traversing the DOM

// Using cy.contains()

// Using cy.findByText()

Some common ways to use CSS selectors in Cypress include:

  • Locating elements by tag name: cy.get(‘button’)
  • Locating elements by class name: cy.get(‘.submit-button’)
  • Locating elements by ID: cy.get(‘#email-field’)
  • Locating elements by attribute: cy.get(‘input[type=”email”]’)
  • Combining selectors: cy.get(‘form input.email-field’)
  • Traversing the DOM: cy.get(‘section.products’).find(‘article:first-child’)

XPath vs CSS Selectors – Which One is Better for Cypress?

Following is the  comparison of using CSS selectors and XPath in Cypress, with some guidance on when to choose one over the other:

CSS Selectors in Cypress:

  • Cypress provides built-in support for CSS selectors using the cy.get() command.
  • CSS selectors are generally faster than XPath in modern browsers.
  • CSS selectors are effective for targeting elements using various attributes such as tag names, classes, IDs, and attributes themselves.

XPath in Cypress:

  • You can employ the cy.xpath() command to utilize XPath in Cypress.
  • XPath proves more potent and adaptable when tackling complex or dynamic web structures.
  • XPath expressions can handle conditions, functions, and complex relationships between elements more easily than CSS selectors.
  • XPath may be more resilient when dealing with frequently changing or dynamically generated content.

When to use CSS selectors in Cypress:

  • When targeting elements based on simple attributes, classes, or IDs.
  • When the web page structure is static and well-defined.
  • When performance and readability are critical factors.
  • When working with modern web applications that adhere to best practices for HTML and CSS.

When to use XPath in Cypress:

  • When targeting elements based on complex conditions or relationships that are difficult to express with CSS selectors.
  • When dealing with dynamic or frequently changing web content.
  • When working with legacy or non-standard web applications that have complex or irregular HTML structures.

When compatibility with older browsers or specialized environments is a concern.

In practice, many Cypress users favour CSS selectors for most scenarios due to their simplicity, readability, and performance advantages. However, XPath can be a valuable tool when dealing with edge cases or complex web structures.

Best Practices for XPath And CSS Selector Techniques In Cypress

Following are the best practices to follow for XPath And CSS selectors in Cypress:

  • It’s generally recommended to prioritize CSS selectors over XPath when locating elements in Cypress tests. CSS selectors tend to be more concise, easier to read and maintain, and widely adopted in web development practices. Reserve XPath selectors for situations where CSS selectors are inadequate or impractical for your specific use case.
  • Always opt for unique identifiers such as IDs or data-test attributes whenever feasible to locate elements in Cypress tests. These identifiers are less susceptible to changes when the application’s structure or styling is updated, enhancing the resilience of your tests.
  • If unique identifiers like IDs or data-test attributes are unavailable, consider using semantic selectors based on the element’s role or purpose within the application. This approach enhances the readability and maintainability of your tests.
  • Avoid relying solely on the text content of elements to locate them, as this approach can lead to brittle tests. Text can change due to localization or application updates, causing your tests to break.
  • Exercise caution when using selectors based on styling, such as class names or CSS attributes. These selectors can be more prone to changes because styles may be updated more frequently than structural or semantic elements.
  • Combine selectors judiciously when needed to precisely target elements. This approach is particularly helpful for addressing complex or dynamically generated structures within the webpage.
  • Utilize the relationships between parent and child elements to locate a specific element within a known parent container effectively.
  • Take advantage of Cypress’s Selector Playground tool, which offers a convenient way to visually inspect elements on the page and generate corresponding selectors.
  • In complex scenarios where CSS selectors may not suffice, XPath can be a powerful alternative due to its ability to handle intricate conditions or navigate hierarchical structures effectively.

When dealing with complex testing scenarios that require intricate usage of XPath or CSS selectors in Cypress, maintaining compatibility across different browsers and environments can pose a challenge.

Leveraging platforms like LambdaTest, It is an AI-powered test orchestration and execution that runs your Cypress tests smoothly.


The decision between CSS selectors and XPath hinges on your project’s specific requirements, the complexity of the web application under test, and the trade-offs among performance, maintainability, and compatibility. Often, a blend of CSS selectors and XPath proves most effective, capitalizing on the strengths of each technique where applicable.

Cypress facilitates the use of both CSS selectors and XPath, empowering developers and testers to select the most fitting approach for their requirements. By mastering both methods and grasping their pros and cons, you can develop robust and maintainable test automation scripts adept at locating and interacting with web elements, ensuring thorough testing of your web applications.

The choice between CSS selectors and XPath is ultimately up to you and the specific needs of your testing scenario. It’s generally recommended to start with CSS selectors, as they’re well-integrated into Cypress and often provide a straightforward approach. But don’t hesitate to reach for XPath when the going gets tough, or even combine the two when it makes sense.

Read more on KulFiy

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.