So I know that you can do:
if ($(selector).length>0) {
// Do something
}
But is there a more elegant method?
So I know that you can do:
if ($(selector).length>0) {
// Do something
}
But is there a more elegant method?
Yes!
jQuery.fn.exists = function(){return jQuery(this).length>0;}
if ($(selector).exists()) {
// Do something
}
There you go!
This is in response to: Herding Code podcast with Jeff Atwood
You can use:
if ($(selector).is('*')) {
// Do something
}
A little more elegant, perhaps.
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)) { }
Just found this in the FAQ:
http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_test_whether_an_element_exists.3F
if ( $('#myDiv').length ) { //do something }
you could also use the following. If there are no values in the jQuery obj array then getting the first item in the array would return undefined.
if ( $('#myDiv')[0] ) { //do something }
In JavaScript, everythig is truthy or falsy and for numbers, 0 means false, everything else true. So you could write:
if ($(selector).length)
and you don't need that "> 0" part.
I have found that sometimes .length
throws an error, but [element locator].size() > 0
works reliably