views:

785

answers:

2

XPath can do everything querySelector can do, and more, so when would you ever choose the latter? I haven't seen any speed benchmarks comparing the two, so right now I'm choosing based on syntax conciseness, which seems kind of arbitrary.

Edit: I probably should have stated that I'm writing Greasemonkey scripts for Firefox, so I'm not worried about cross-browser compatibility, and would rather not include any libraries.

+2  A: 

What browser are you using? In Safari (or the iPhone), querySelector and querySelectorAll are much faster than XPath. IE doesn't support XPath at all, and IE6 and IE7 don't support querySelector. The fastest cross-browser selector engine is Sizzle, created by John Resig. Sizzle is also the main selector engine used in jQuery. It uses querySelector where appropriate and normal DOM methods where querySelector is unavailable.

Yehuda Katz
+1  A: 

In terms of functionality your best bet will be to use a library that includes a selector engine, and many of them (e.g. MooTools, Dojo, Prototype) are already using XPath internally to execute some classes of queries. You should be able to count on a good library choosing the fasted method for you.

XPath might be able to do everything that querySelector can do (I think this statement is a bit suspect, but that is beside the point) but querySelector and querySelectorAll are not supported by all browsers, so really we should be comparing XPath to native DOM querying methods (i.e. getElementsByTagName, getElementById, querySelector, standard traversal and filtering methods, etc.)

Using native DOM filtering methods requires knowledge of browser quirks and limitations and quickly becomes impractical for complex querying unless you use a library (e.g. jQuery or MooTools) to iron out the inconsistencies. The reason that native DOM techniques (whether through a proxy like jQuery, or custom implementations) are often chosen over XPath is that they do offer much more flexibility than XPath. For example, if you want to filter for checked inputs, "hidden" elements or disabled inputs XPath comes up short but jQuery gives you :checked, :hidden and :disabled pseudo-classes.

Prestaul