When to use CSS selectors vs. XPath ID's

You might be wondering if it's advantageous to use CSS selectors or XPath ID's for element selection, but this mainly depends on the context in which they're being used! Both are powerful tools used to access web elements and have access to the entire DOM of a site, so objectively none of the two is "better". However, some things are easier to express with CSS selectors and others are easier to express with XPath ID's.

When to use CSS selectors:

  • Usually faster than XPath
  • Easier to learn/understand syntax - they are more readable
  • Heavily used in development (JQuery is heavily reliant on CSS)
  • Generally, CSS selectors can do almost everything an XPath ID can do

CSS, which stands for Cascading Style Sheets, is a language that is used for describing the presentation details of a document that is written in markup language such as XML or HTML. It describes how HTML elements are displayed on screen. CSS aids in the design, layout and variations in display for different devices and screen sizes. You can read more about this here.

Example CSS selectors (courtesy of W3Schools):

Selector

Example

Description

.class

.intro

Selects all elements with class="intro"

#id

#firstname

Selects the element with id="firstname"

[attribute~=value]

[title~=flower]

Selects all elements with a title attribute containing the word "flower"

When to use XPath ID's:

  • Cases where you only want to support one selector type
  • Your browser does not fully support CSS or all the CSS selectors you need (older browsers such as IE, for example, doesn't support all CSS selectors)
  • You need to do a task that only an XPath would support (finding an element by moving back up the DOM)

XPath is an XML path language, and is a query language that is used to select nodes from an XML document. Finding elements based on their XPath ID generally works very well and is flexible. XPath expressions look very similar to the ones you would see when working with a traditional computer file system. However, there are areas where using this as a main locator strategy can be hindered by its slow performance.

Example XPath Selectors

Example XPath selectors and syntax can be found here.

Within the browsers:

  • Chrome and FireFox are tuned for faster CSS performance
  • XPath operates faster in IE 11

One of the main differentiators between XPath and CSS is that with XPath, you can search elements both forwards and backwards in the DOM hierarchy, whereas CSS only operates in the forward direction. What this means is that with XPath, you could locate parent elements by using child elements. However, across almost all the browsers, nested sibling traversal and table traversal done via XPath ID's is expensive.