AlexStack
AlexStack

Reputation: 17381

Jquery shorthand for .size()>1

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?

Upvotes: 0

Views: 379

Answers (4)

mnowotka
mnowotka

Reputation: 17228

Use 'has' selector.

You can write:

$(':has(.blahblah:eq(1))') 

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382696

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
}

Upvotes: 0

Manuel van Rijn
Manuel van Rijn

Reputation: 10305

another option will be

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

if your goal is less typing

Upvotes: 1

Chuck Norris
Chuck Norris

Reputation: 15190

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.

Upvotes: 3

Related Questions