This behavior in some places is called "coalescing". Here's a generic jQuery plugin that does it for you (editing after great feedback, see the comments).
// The namespace function
jQuery.coalesce = function(selectors){
var out;
$.each(selectors, function(i, v){
var el = jQuery(v);
if (el.length) {
out = el;
return false;
}
});
return out || jQuery();
};
// The jQuery plugin
jQuery.fn.coalesce = function(){
return jQuery.coalesce(this.selector.split(",")); //a little brittle
};
So, in a world where #foo
doesn't exist, and a
and div
do, if you do:
jQuery.coalesce(["#foo", "a", "div"])
That returns jQuery("a")
if #foo
doesn't exist, or jQuery("#foo")
if #foo
does exist.
If you require using it in the middle of the chain, you can use $("#foo, a, div").coalesce()
, but its vulnerable to commans within the selectors themselves.
split()
call, but I believe this is heavily optimized down to native code in browser code, and isn't really something to worry about. – Blythebm