In jQuery, I already know how to check if an element exists by using the length property on the jQuery object returned by a specific selector.
However, internally, this means that jQuery first grabs all the objects and then gets the length. For performance reasons, I want to see if just 1 element exists, I don’t need to grab the rest.
How can I do that?
See related question: Optimize jQuery selector with :first
I’ve branched off a jsPerf test that compares
$("xxx:first")with$("xxx").first()to see if jQuery is optimized to bail out early from matching when:firstis used. It doesn’t seem be have that optimization:http://jsperf.com/does-first-boost-your-selector/4
Update:
.eq(0)vs:eq(0)behaves the same way.So, you’re probably out of luck. There does not seem to be a more efficient way to pick/check the first match. Unless of course, you have the option to constrain your selector to classes and ids, as others have noted, and as it has also been noted in the other question that I linked to.