When creating a custom find step, you might be wondering if it's advantageous to use CSS selectors or XPath expressions for element selection. While both are powerful tools used to access web elements and have access to the entire DOM of a site, neither of them is objectively "better". Ultimately, the decision to use CSS or XPath depends on the context.
Read on to learn more about when to use CSS selectors vs. XPath expressions.
Before you use a CSS query or XPath expression to find a specific element and interact with it, try using Configure Find to tell mabl what attributes the element that you are looking for should have.
Configure Find handles a lot of the same use cases as steps that use CSS or XPath while also being more maintainable, since you don't need to know CSS or XPath to troubleshoot the step if something goes wrong.
When to use CSS selectors
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.
Some reasons to use CSS selectors include:
- Usually faster than XPath
- Syntax is easier to learn and understand
- Heavily used in development - JQuery is heavily reliant on CSS
- Can do almost everything an XPath expression can do
- Targeting elements in a shadow DOM - elements within a shadow DOM cannot be targeted with XPath
W3Schools is a great resource for learning more about CSS selectors and syntax.
When to use XPath expressions
XPath, which stands for XML path language, 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.
Some reasons to use XPath expressions include:
- Finding an element by text
- Locating a parent element by using a child element
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.
Devhints.io has a great resource for learning more about XPath expressions and syntax.