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).
So, in a world where
#foodoesn’t exist, andaanddivdo, if you do:That returns
jQuery("a")if#foodoesn’t exist, orjQuery("#foo")if#foodoes 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.