Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: is there a concise way to conditionally use a 2nd selector if a 1st selector comes back empty?

In python, I can do the following, to conditionally use a 2nd list if a 1st one is empty:

>>> x = [ ] or [1, 2]
>>> x
[1, 2]

In javascript, however,

>>> x = [ ] || [1, 2];
[ ]

So, if the "or trick" is off the table, I'm wondering whats the most concise way to do something like the following if-javascript-were-python-this-would-work pseudocode:

$elems = $('first-selector') || $('second-selector')
like image 834
B Robster Avatar asked Mar 30 '12 20:03

B Robster


1 Answers

var elems = $("first-selector");
if(!elems.length) {
    elems = $("second-selector");
}

is not concise enough?

How about writing a little jquery extension?

$.fn.or = function(selector) {
    if (this.length) {
        return this;
    }

    return $(selector);
}

var elems = $("first-selector").or("second-selector")
like image 89
bhamlin Avatar answered Oct 05 '22 22:10

bhamlin