Ticket #11785 (closed bug: patchwelcome)
.findOne() method
| Reported by: | dmethvin | Owned by: | |
|---|---|---|---|
| Priority: | undecided | Milestone: | None |
| Component: | unfiled | Version: | 1.7.2 |
| Keywords: | Cc: | ||
| Blocking: | Blocked by: |
Description
There would certainly be a performance benefit to this on platforms that support querySelector() which is most of them these days.
http://forum.jquery.com/topic/why-there-is-no-jquery-findone-method-or-smth-similar
Also, perhaps we could automatically change $("anything:first") to use querySelector()?
Change History
comment:2 Changed 13 months ago by rkatic
I think findFirst() is more appropriate then findOne() for several reasons: 1) It is more similar to the .first() method and the :first filter. 2) it removes any doubt in case of not simple selectors. Consider ".boo, .foo". We expect the ".foo" element if it precedes the ".boo" one, becouse it is how querySelector() works.
So, I suggest three two additions:
- jQuery.findFirst(), that behaves like jQuery.find("...")[0] || null
- jQuery.fn.findFirst()...
jQuery.first(), that returns jQuery( jQuery.findFirst("...") )
Note how those additions would play nicely with the existent API. For example:
- $(".foo").find(".boo:first") or $(".foo").findFirst(".boo")
$(".boo").first() or $.first(".boo")
EDIT: Rethinking, I come with the conclusion that jQuery.first() would introduce confusion to the API, since .first() is for "filtering" and not for "searching"...
comment:3 Changed 13 months ago by rwaldron
After some consideration and re-reading the forum post, I dont think this makes sense. jQuery's API expects jQuery objects, querySelector is a node, not a list of nodes - so it wouldn't work with the current API anyway... Unless we shove it into a jQuery object, then we're back to good ol' jQuery(selector)
comment:4 Changed 13 months ago by dmethvin
I did a quick jsperf to see if it seemed worth the effort. I thought for sure that it would be. Now I am not so sure, can anyone see something wrong here?
http://jsperf.com/findone-vs-findall
Once these are wrapped in the overhead of Sizzle I doubt they will be that much different.
comment:5 Changed 12 months ago by dmethvin
- Status changed from new to closed
- Resolution set to patchwelcome
Per the jsperf I did, it doesn't seem worth adding this method since it's not faster. If someone wants to come up with a full implementation and perf tests proving otherwise we can reopen.
comment:6 Changed 7 months ago by jquery@…
Putting aside performance for a second, am I the only one that often will look for a single element on the page?
I typically either want to process any number of entries (0, 1 or more), or 1; in the later case, a findOne would be helpful if it raised an exception if none is found.
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

+1 to this