JQuery equivalent || or?? operator

Using regular JavaScript, I can do the following:

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

If the first DOM search returns null , which is false, the second search is evaluated.

The jQuery $() function always returns an object of type jQuery, similar to an array, even if no elements are matched. Even if this object is empty, this object is not false, so the following expression will never evaluate the right side:

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

So what is the idiomatic way to do this kind of fallback when using jQuery?

+4
source share
3 answers

Checking the number of matching / returned items will tell you if your selector matches something or not ... fallback is a simple plug-in for a utility that allows you to do this gracefully ...

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

The best part of this feature is that you can combine as many as necessary until you find a matching item.

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

+7
source
 var ninjaTurtle = $('#raphael').length ? $('#raphael') : $('#leonardo'); 
0
source

I see no way to do this. The shortest thing that comes to my mind:

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

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


All Articles