In fact, if you find yourself doing a lot of if(something exists) { ... } else { ...}, you might want to consider trying to move some of your code into a plugin. Most jQuery functions/plugins already deal with the if(exists)... part by simply not executing if nothing is selected. If you really want the 'else' part, you could imagine a simple plugin, something like (untested):
$.fn.ifEmpty = function(f) { if(this.length == 0) f.apply(this); return this; } And use it like this: $('#foo').show().ifEmpty(function() { alert("foo doesn't exist"); }); Which would show the element with ID foo, or show an alert if the element doesn't exist. Equivalent to: var $foo = $('#foo'); if($foo.length > 0) { $foo.show(); } else { alert("foo doesn't exist"); } Just an idea. --Erik On 7/9/07, Erik Beeson <[EMAIL PROTECTED]> wrote:
> Another idea is that if the seletor doesn't select any elements, > return null (as does getElementById() in that case): > ... > but that may not be backward compatible. Of what use is an empty > jQuery object? An empty jQuery object doesn't break chainability: $('#foo').hide(); Will hide the element with ID foo if it exists. Otherwise, it does nothing. If null were returned, that would generate a javascript error, so you would have to always check for the existence of the element if you wanted to be sure you didn't generate an error. This is one of the sweetest features of jQuery. --Erik