Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find fallback element in jQuery

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"?

like image 782
Tgr Avatar asked Dec 22 '22 09:12

Tgr


2 Answers

If you expect only one element you can do this:

var element = $(findElement()[0] || findSomeOtherElement()[0] || makeALastAttempt()[0]);
like image 67
Arnaud Le Blanc Avatar answered Dec 24 '22 01:12

Arnaud Le Blanc


Why not using:

jQuery.fn.exists = function(){
if(this.length>0) 
    return this;
return false; };


var a = ($(selector1).exists() || $(selector2).exists());
like image 32
JohnJohnGa Avatar answered Dec 24 '22 02:12

JohnJohnGa