Find fallback item in jQuery

JavaScript has very good syntax for backups and default values ​​if failed calls return a false value:

var element = findElement() || findSomeOtherElement() || makeALastAttempt(); 

JQuery selectors, however, are true even when they are empty.
Is there an elegant way if you say "I want an element in this selector, and if it does not exist, then an element in this selector"?

+4
source share
5 answers

Why not use:

 jQuery.fn.exists = function(){ if(this.length>0) return this; return false; }; var a = ($(selector1).exists() || $(selector2).exists()); 
+2
source

If you expect only one item, you can do this:

 var element = $(findElement()[0] || findSomeOtherElement()[0] || makeALastAttempt()[0]); 
+3
source

Select an element named anchorName , and if it is not found, select another element with the identifier #anchorName

 $("[name=anchorName], #anchorName").first() 
+1
source

No. Sorry, you have to use the .length property. This is a side effect of Javascript that evaluates all objects as true, and obviously the jQuery selector is a functionally object. However, the resulting syntax is not so bad:

 $(function(){ var element = $('.findElement'), otherElement = $('.findSomeOtherElement'), lastAttempt = $('.lastAttempt'); var elegance = (element.length && element) || (otherElement.length && otherElement) || (lastAttempt.length && lastAttempt); elegance.css('border','1px solid green'); }); 

Demo

0
source

It turns out the answer is much closer to the desired.

 var fallback = function(options){ var numOfOptions = options.length; if (numOfOptions == 2){ return (options[0].length > 0)? options[0] : options[1]; }else if (numOfOptions > 2){ return fallback(options.slice(1)); }else if (numOfOptions == 1){ return options[0]; }else{ return $(); } }; fallback([$(selector1),$(selector2),$(selector3)]); 
0
source

Source: https://habr.com/ru/post/1369462/


All Articles