Like selector chains with an OR clause (alternative result set if main is empty)

What I have now:

var result = $('selector1'); if (result.length == 0) result = $('selector2'); 

but it wins the chain.

Question: how to get the same result with jQuery chaining?

I cannot use $('selector1, selector2') because it will always select a result set for both selectors, whereas I need selector2 results only if there are no matching elements for selector1 .

+6
source share
4 answers

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.

+3
source

If you need to, this would do this:

 $(function(){ var r = $('selector1'); if (r.length == 0) r = $('selector2'); return r; }()); 

However, I do not think that the chain in your example will be defeated. Chaining is not all-all-ending, and investing in an inquiring choice, such as the one above, is more for obfuscating code than for simplification.

0
source
 var result = $('selector1'); ( result.length ? result : $('selector2') ).css('color', 'red'); 
0
source

I do not believe that you can do it exactly the way you want, only with pure jQuery, but you can get some of the functions you are looking for using the advanced jQuery selectors that allow you to choose based on negation and Boolean operators. Check out http://api.jquery.com/category/selectors/jquery-selector-extensions/ .

0
source

Source: https://habr.com/ru/post/900063/


All Articles