ded/qwery — Issue #71: Argument to only return first match
Author: rvagg
Created: 2012-02-09 00:04:42+00:00
State: open

@benvinegar's [query on Twitter](https://twitter.com/#!/bentlegen/status/167333474901041152) about being able to return the *first* match only got me thinking that it may not be that difficult to implement and would actually be quite helpful in many situations.

So here's a first go at hacking a solution, no tests and begging for review by other eyes: https://github.com/rvagg/qwery/compare/master...first

The basic idea is to use `querySelector()` where available, then we fall back to `_qwery()` for odd queries or where `querySelector()` isn't available. We then shortcut the various paths to matches when we have asked for a `first` and have found a result. There's a few places this needs to be done and my implementation isn't quite optimal because there's currently no way to halt an `each()` call so we end up doing a bunch of useless loops, but that could be easily fixed by special handling of `return false`.

Of course, there's still the document-order problem (see #63), so any documentation around use of this functionality would need to stress that you may not get the same result for queries with groups in old vs new browsers because of the differences between `querySelector()` and what `selectNonNative` does with splitting the query... Or, someone could fix #63.

Also put in a simple `$.first('selector')` to the Ender bridge.

In its current form it adds 109 bytes to minified gzipped Qwery.

And, FWIW, NWMatcher has a neat callback feature where you pass in a function that gets called on each match so you can process elements one by one but if you return a `false` then it'll halt processing so you can use it to implement a `first()` which halts on first match, see the NW [Ender bridge](https://github.com/dperini/nwmatcher/blob/master/lib/ender/bridge.js#L95-97).