Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery length > 0

Tags:

jquery

I desided to make my code clearer by replacing
if (wrappedSet.length > 0)
to something like
if (wrappedSet.exists())
Is any native jq function for this? Or the only way is to extend it using $.fn.exists = ... ?

like image 521
Sergey Metlov Avatar asked May 08 '26 22:05

Sergey Metlov


2 Answers

You could simply use

if (wrappedSet.length) 

That will evaluate to TRUE if you have 1 or more elements and to FALSE if you have 0 elements

like image 158
JohnP Avatar answered May 11 '26 14:05

JohnP


The function size does exactly this. On the other hand, why do you want to do this? The extra function call would reduce performance (albeit by an infinitesimally small amount) with no particular gain.

You could just do this:

if (wrappedSet.length) {

since 0 evaluates to false and any other number evaluates to true.

like image 43
lonesomeday Avatar answered May 11 '26 14:05

lonesomeday