Jørn Schou-Rode
Jørn Schou-Rode

Reputation: 38346

jQuery equivalent of || or ?? operator

Using plain JavaScript I can do stuff like this:

var ninjaTurtle = document.getElementById('raphael') ||
                  document.getElementById('leonardo');

If the first DOM lookup returns null, which is falsy, the second lookup is evaluated.

The jQuery function $() always returns i jQuery array-like object, even when no elements are matched. Even when empty, this object is not falsy, hence the following expression will never evaluate the right hand side:

var ninjaTurtle = $('#raphael') || $('#leonardo');

So, what is the idiomatic way of doing this kind of fallback when using jQuery?

Upvotes: 4

Views: 238

Answers (3)

WTK
WTK

Reputation: 16971

I don't see the way of doing it. The shortest things that comes to my mind is:

var ninjaTurtle = $('#raphael').length ? $('#raphael') : $('#leonardo');

Upvotes: 0

Teja Kantamneni
Teja Kantamneni

Reputation: 17472

Checking the matched/returned element count will tell you if your selector matched something or not... fallback is a simple utility plugin which lets you do that gracefully...

jQuery.fn.fallback = function(elem) {
    return 0 < this.length ? this : $(elem);
};

The best part of this function is you can chain as many as needed until you find a matched element..

$('#raphael').fallback('#leonardo').fallback('#kilik').dosomething();

Upvotes: 7

Konerak
Konerak

Reputation: 39763

var ninjaTurtle = $('#raphael').length ?  $('#raphael') : $('#leonardo');

Upvotes: 0

Related Questions