You might be wondering if it's advantageous to use CSS selectors or XPath expressions 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 expressions.
When to use CSS selectors:
- Usually faster than XPath
- Easier to learn/understand syntax. In other words, 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
- If you are targeting an element in a shadow DOM. (Elements within a shadow DOM cannot be targeted with XPath.)
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):
|Selects all elements with class="intro"
|Selects the element with id="firstname"
|Selects all elements with a title attribute containing the word "flower"
When to use XPath expressions:
- 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 expression 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 expressions and syntax can be found here.
Within the browsers
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 with XPath expressions is expensive.