JavaScript has very nice syntax for fallbacks and defaults, as long as unsuccessful calls return a falsy value:
var element = findElement() || findSomeOtherElement() || makeALastAttempt();
jQuery selectors are, however, truthy even when they are empty.
Is there an elegant way if saying "I want the element at this selector, and if it does not exist, then the element at that selector"?
If you expect only one element you can do this:
var element = $(findElement()[0] || findSomeOtherElement()[0] || makeALastAttempt()[0]);
Why not using:
jQuery.fn.exists = function(){
if(this.length>0)
return this;
return false; };
var a = ($(selector1).exists() || $(selector2).exists());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With