XPath vs. CSS Selectors

CSS selectors are a good thing. They are massively optimized and built in to the browsers and they run blazingly fast.

XPath on the other hand isn't built in to all browser, most prominantely not in IE. Anyone who wishes to run an XPath query against IE needs to first inject a tool like JavaScript-XPath.

But the more prominent problem is that XPath still has some features which aren't easily replaced by equivalent CSS selector expressions:

  1. Finding element based on its text content, such as //table/tr/td[contains., "foo")/../td[2]/input.
  2. Finding any element relative to its parent or ancestor, for example ./../div[2].
  3. Complex conditional statements, such as looking up all classes of A, but not A combined with B or C.
  4. Subqueries in the style of //li[./a] giving you all li's with a inside, or li[.//a] giving you all li elements that have a as a child or descendant.

Also see the related Stack Overflow answer by Jim Evans.