This behavior is called βcoalescingβ in some places. Here is a generic jQuery plugin that does this for you (editing after excellent feedback, see 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 does not exist, and a and div do, if you do:
jQuery.coalesce(["#foo", "a", "div"])
This returns jQuery("a") if #foo does not exist, or jQuery("#foo") if #foo exists.
If you need to use it in the middle of the chain, you can use $("#foo, a, div").coalesce() , but its vulnerability to commas in the selectors themselves.
Yahel source share