9

With JQuery, to check if a selector exists, I do something like :

if ($(selector).length > 0) { ... }

But I suppose it's maybe not the best way because I just want to know if a selector exists, not how many. Is there a way to stop the search at the first occurrence found for optimization reason ?

Thank you!

EDIT: To clarify : I'd like to avoid the "length" method because it checks in all the DOM. I just want to stop when one occurrence is found

Mathieu Mahé
  • 2,647
  • 3
  • 35
  • 50
  • 1
    possible duplicate of [Is there an "exists" function for jQuery](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – kapa Nov 09 '11 at 17:56

3 Answers3

8

There's no more efficient method to let jQuery stop after finding a matching element.
It's not even possible in Vanilla ("pure") JavaScript to limit document.getElementsByTagName("p") to match only one element, without having a worse performance.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 1
    Furthermore, there's no compelling reason to do so. It's great to look for opportunities to optimize, but we're talking not just milliseconds but nanoseconds here. The operation $('span').length on a test page with 160 spans on it took "1 millisecond". 1 millisecond is the shortest time interval .getTime() will give us, so it could be even less. – Greg Pettit Nov 09 '11 at 18:18
1

In theory you could append :first to your query to limit results ( http://api.jquery.com/first-selector/ ), but it would actually make your query slower, because it prevents jQuery from using the native querySelectorAll() function of modern browers.

biziclop
  • 14,466
  • 3
  • 49
  • 65
-4

Use this,

if( $('#idofelement'))  or
if( $('.classname')  )
Exception
  • 8,111
  • 22
  • 85
  • 136
  • `.size()` is no different than `.length()`. Look in the jQuery code and they are the same. – jfriend00 Nov 09 '11 at 18:01
  • 3
    This answer is incorrect. When an element does not exists, and object with **length=0** is returned. An object is always a truthy value, so your assertion is always true. – Rob W May 24 '12 at 06:50
  • @RobW But it is not fair, returning array element even if I pass `id` is bit misleading. I agree if it is returning me array of elements if I pass class name or tag name etc.. – Exception Feb 15 '13 at 05:54
  • jQuery does not have a special return value for `id`s. See it in this way, you're asking for "a jQuery list of all elements which match the given selector". Which could be an empty list, if there's no match. – Rob W Feb 15 '13 at 09:06
  • @RobW Yes, I agree with you.. In jQuery selector point of view this is reasonable.. :-) Thanks – Exception Feb 15 '13 at 09:19