Take the 2-minute tour ×  How can I check the existence of an
element in jQuery?  The current code that I have is this:  if
($(selector).length>0) {     // Do something  Is there is a more
elegant way to approach this? Perhaps a plugin or a function?
share|improve this question if ($(selector).length) {} is the
most elegant and the fastest. –  gradbot Jun 21 '10 at 3:21
Note: In jQuery versions older than 1.4, $('').length // is 1
(ref). So in that case use $(selector || []).length. –  Mottie
Feb 21 '13 at 18:43 if($(selector)[0]) {} I always use this.. – 
Mr_Green Sep 4 '13 at 11:57 To avoid recursion maybe it will be
best: if ( !$(selector).length ) { return; } // Do something – 
Gabotron Nov 29 '13 at 15:22 @bergie3000 You're testing the
selector speed and not the comparison. jsperf.com/length-vs-
length-0-for-existence-of-element/2 –  gradbot Feb 21 at 3:41
21 Answers 21  In JavaScript, everything is truthy or falsy and
for numbers, 0 means false, everything else true. So you could
write:  if ($(selector