In Mootools, I'd just run if ($('target')) { ... }
. Does if ($('#target')) { ... }
in jQuery work the same way?
views:
13257answers:
6
+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
2008-11-18 19:17:09
+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
2008-11-18 19:20:29
Thanks! Didn't find that one in my search, but that's exactly what I need.
One Crayon
2008-11-18 19:30:39
what is the point in this when .length does exactly the same?
redsquare
2010-05-27 03:19:43
This is one of the sillier plugins I've ever seen...
Alex Sexton
2010-05-27 04:26:54
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
2010-05-30 04:13:13
I have reworded the reply to emphasize that $.fn.exists is slower.
Pat
2010-05-31 14:58:04
height of plugihness
Quintin Par
2010-06-03 06:36:49
+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
2009-01-14 19:43:58