> 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. The target audience for an exists() function would be new comers to jQuery. Those are generally a little scared about writing their own 'plugin' even so there isn't much to be scared about I think and I'm just making this assumption here ; ).
Anyway, there are situations where plugins are not enough. For example if you have to modify other elements in case a certain screen element exists then a plugin won't really help you a lot unless it's very app-specifc. -- Felix -------------------------- My Blog: http://www.thinkingphp.org My Business: http://www.fg-webdesign.de Erik Beeson wrote: > > 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 >> >