views:

13257

answers:

6

In Mootools, I'd just run if ($('target')) { ... }. Does if ($('#target')) { ... } in jQuery work the same way?

+16  A: 

no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length

if ( $('#someDiv').length ){

}
redsquare
+19  A: 

As the other commenters are suggesting the most efficient way to do it seems to be:

if ($(selector).length ) {
    // Do something
}

If you absolutely must have an exists() function - which will be slower- you can do:

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

Then in your code you can use

if ($(selector).exists()) {
    // Do something
}

As answered here

Pat
Thanks! Didn't find that one in my search, but that's exactly what I need.
One Crayon
what is the point in this when .length does exactly the same?
redsquare
This is one of the sillier plugins I've ever seen...
Alex Sexton
Your `$.fn.exists` example is really, really horrible, and I hope nobody uses it. You’re replacing a property lookup (cheap!) with two function calls, which are much more expensive—and one of those function calls recreates a jQuery object that you already have, which is just silly.
snover
I have reworded the reply to emphasize that $.fn.exists is slower.
Pat
height of plugihness
Quintin Par
A: 

Alternatively:

if( jQuery('#elem').get(0) ) {}
J-P
+4  A: 

if you used:

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

you would imply that chaining was possible when it is not.

This would be better

jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
Jon Erickson
+1  A: 

if($('#elem')[0]) {}

Sean Curtis
A: 

Yet another way:

$('#elem').each(function(){
  // do stuff
});
PhilT