0

I'm working on a code with a lot of $(".blahblah").size()>0 conditions in it. I was wondering if there is a JQuery shorthand for it that eliminates the need to type >1.

There is a suggestion here: http://forum.jquery.com/topic/selector-exists-would-be-a-nice-addition

Something like $(...).exists() can be handy. Is there such a thing? I couldn't find it on the Internet and I was wondering if someone knows a trick or anyone from JQuery team who knows if such feature is planned to be added?

PS. I have read this: Is there an "exists" function for jQuery?

Community
  • 1
  • 1
AlexStack
  • 16,766
  • 21
  • 72
  • 104
  • also see http://stackoverflow.com/questions/299802/how-do-you-check-if-a-selector-exists-in-jquery – Manuel van Rijn Apr 11 '12 at 07:07
  • 1
    The forum thread you link also links to a [bug ticket](http://bugs.jquery.com/ticket/3842) which is closed "because `is()` already provides this functionality" (so I guess that's as close as you'll get to a built-in function). – Jeroen Apr 11 '12 at 07:07

4 Answers4

3
function moreThanOne(selector){
  return $(selector).length > 1;
}

The solution is to use function for that and also you can use length instead of size().

From Jquery's documentation

The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call.

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
1

another option will be

if($(".blahblah")[0]) { ... }

if your goal is less typing

Manuel van Rijn
  • 10,170
  • 1
  • 29
  • 52
0

You can create your own exists function like this:

function exists(selector){
  return jQuery(selector).size() > 0;
}

And then you can use it like:

if (exists(".blahblah")) {
  // it exists
}

Added to jQuery fn:

jQuery.fn.exists = function(){
    return this.length > 0;
}

To use:

if ($(".blahblah").exists()) {
  // it exists
}

You can also use length property for which you don't need to type > 0:

if ($(".blahblah").length) {
  // it exists
}
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • thanks but I would go with the jQuery.fn.exists = function(){return this.length>0;} solution because of readability. – AlexStack Apr 11 '12 at 07:05
  • @AlexStack: Yeah that's better, I have updated answer with that :) BTW, you can also simply do `if ($(".blahblah").length)` without need to type `> 0` – Sarfraz Apr 11 '12 at 07:06
  • yes, that's a good suggestion, but for code readability, I prefer to have `>0` the reason I'm looking for the `exist()` function in the first place is readability rather than speed. – AlexStack Apr 11 '12 at 09:54
0

Use 'has' selector.

You can write:

$(':has(.blahblah:eq(1))') 
mnowotka
  • 16,430
  • 18
  • 88
  • 134