Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to chain selectors with OR condition (alternative result set if main is empty)

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.

like image 409
lxa Avatar asked Oct 25 '11 16:10

lxa


1 Answers

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.

like image 176
Yahel Avatar answered Sep 16 '22 17:09

Yahel