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?
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…
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();