CSS syntax is awesome for two reasons:
- It is an order of magnitude faster and less resource intensive than the more complex XPath.
- When what you want to find can be found with a css selector, a corresponding XPath query doing the same would most of the time be much longer and harder to read.
Case in point: take this css selector: h1.header > a[rel~="author"]
Its shortest functional XPath equivalent would be //h1[contains(" "+normalize-space(@class)+" "," header ")]/a[contains(" "+normalize-space(@rel)+" "," author ")]
…which is both much harder to read and write.
If you wrote this XPath instead: //h1[@class="header"]/a[@rel="author"]
…you would incorrectly have missed markup like <h1 class="article header"><a rel="author external" href="/mike">...</a></h1>
When you really need XPath, though, it's the only option, unless you want to walk around the DOM manually with code (which gets hideous fast).
Personally (and I am one of the maintainers of Greasemonkey), I use the very tiny on.js
library for all my node slicing needs - which gives me a combination of both XPath (for when I need that), and CSS (which I tend to use almost all the time) – mostly because it lets me separate out all the code that deals with digging up parts of a page I need to digest, into the script header so my code gets served all the stuff it needs, and can be all about actually doing fun or great things to web pages.
Web browsers are very heavily optimized for running javascript really fast, and if I were you I would recommend using whatever makes you most efficient and happy as a developer, over what makes the browser run the least amount of code. One of the side benefits of on.js
in particular, though, is that it automatically helps scripts often not get run at all, on pages where the nodes you thought were around, turn out not to be, instead of destroying the page.
querySelector*
anddocument.evaluate
. In the backwards IE world (even counting IE10), native XPath support is still not around for HTML documents, though. – Biernat