CSS Selectors to XPath Cheatsheet

Applies to CrossBrowserTesting SaaS, last modified on January 10, 2023

CSS and XPath can both be used to denote locations in an XML document. These 2 syntaxes help guide your Selenium tests and allow automation to follow your well thought out test strategy. CSS is native to all browsers and specifically built for rendering in browsers, while XPath can give your Selenium test an exactness that is sometimes lacking in CSS. We put together a few tables to help translate XPath to CSS and vice versa. For browser testing, this translation can be especially effective for designers, developers and testers working together during the development and testing phase.

General:
What It Does XPath CSS
All HTML /html html
Body of Page /html/body body
Element box absolute reference /body/…/box body > … > .box
Any element matching box box box
Any element in the document * *
ID of an element [@id='green-background'] #green-background
Class of an element [@class='Box'] .box
Any element matching title that is a descendant of box box//title box > title
Any element matching title that is a child of box box/ title .box .title
Any element matching title immediately preceded by box element box/following-sibling::*[1]/self::title .box + .title
Image element //img img
Predicates
What It Does XPath CSS
Selects first child element /box/title[1] .box .title:first-child
Selects the last child element /box/title[last()] .box .title:last-child
Selects the second to last child element /box/title[last()-1] .box .title:nth-last-child(2)

See Also

Selenium Best Practices
Selenium and Ruby

Highlight search results