Reputation: 17381
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
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
Reputation: 10305
another option will be
if($(".blahblah")[0]) { ... }
if your goal is less typing
Upvotes: 1
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