Converting CSS to XPath

In web testing, effectively selecting elements within a webpage’s Document Object Model (DOM) is crucial. CheckView supports both CSS selectors and XPath expressions for this purpose. Understanding the differences and similarities between CSS and XPath can enhance your testing strategies. Below is a guide to converting common CSS selectors into their XPath equivalents.

1. Selecting Elements by Tag Name

DescriptionCSS SelectorXPath Expression
Any element*//*
Any <span> elementspan//span
Any <section> elementsection//section

2. Selecting Elements by Attribute

DescriptionCSS SelectorXPath Expression
<input> with type equal to textinput[type=”text”]//input[@type=”text”]
Elements with data-role starting with admin[data-role^=”admin”]//*[starts-with(@data-role, ‘admin’)]
Elements with data-id ending with 123[data-id$=”123″]//*[substring(@data-id, string-length(@data-id) – string-length(‘123’) + 1) = ‘123’]
Elements with title containing tooltip[title*=”tooltip”]//*[contains(@title, ‘tooltip’)]

3. Selecting Elements by ID

DescriptionCSS SelectorXPath Expression
Element with ID header#header//*[@id=’header’]

4. Selecting Elements by Class

DescriptionCSS SelectorXPath Expression
Elements with class active.active//*[contains(concat(‘ ‘, normalize-space(@class), ‘ ‘), ‘ active ‘)]

5. Selecting Elements by Text Content

DescriptionCSS SelectorXPath Expression
<button> with exact text SubmitN/A//button[text()=’Submit’]
<p> containing text WelcomeN/A//p[contains(text(), ‘Welcome’)]

6. Selecting Elements by Hierarchy

DescriptionCSS SelectorXPath Expression
Direct child <li> of <ul>ul > li//ul/li
Descendant <a> within <nav>nav a//nav//a
Adjacent sibling <div> following a <header>header + div//header/following-sibling::div[1]

Additional Tips

  1. CSS Pseudo-classes and Pseudo-elements: CSS selectors like ‘:nth-child()’ or ‘::after’ don’t have direct XPath equivalents. For instance, ‘div:nth-child(2)’ can be translated to ‘//div[position()=2]’ in XPath.
  2. Performance Considerations: CSS selectors are generally faster and more readable for simple selections. XPath offers more flexibility, especially for complex hierarchical selections or when selecting elements based on text content.
  3. Tooling: Utilize browser developer tools to test and refine your selectors. Most browsers allow you to test both CSS and XPath expressions directly in the console.