admin管理员组

文章数量:1295740

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

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

Share Improve this question edited Jun 20, 2014 at 3:15 Brock Adams 93.6k23 gold badges241 silver badges305 bronze badges asked Aug 29, 2011 at 9:41 TgrTgr 28.2k13 gold badges87 silver badges121 bronze badges 1
  • possible duplicate of jQuery equivalent of || or ?? operator – Brock Adams Commented Jun 20, 2014 at 3:11
Add a ment  | 

6 Answers 6

Reset to default 6

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

Will select an element with name anchorNameand if not found select another element with ID #anchorName

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

If you're only wanting a single element as your result, I ended up with:

$('#preferred-element').add($('#fallback-element')).first();

No. Sorry, you'll have to use the .length property. This is a side effect of Javascript evaluating all objects as truthy, and obviously a jQuery selector is functionally an 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

Heres an answer a lot closer to what was actually 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)]);

本文标签: javascriptFind fallback element in jQueryStack Overflow