What I have now:
var result = $('selector1');
if (result.length == 0) result = $('selector2');
but this defeats chaining.
Question is - how do I get same result with JQuery chaining?
I can't use $('selector1, selector2')
, because this would always select result sets for both selectors, while I need results of selector2
only if there are no matching elements for selector1
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With