How can I detect if a selector returns null?

前端 未结 8 1931
无人及你
无人及你 2020-11-27 09:01

What is the best way to detect if a jQuery-selector returns an empty object. If you do:

alert($(\'#notAnElement\'));

you get [object Object

8条回答
  •  余生分开走
    2020-11-27 09:27

    My preference, and I have no idea why this isn't already in jQuery:

    $.fn.orElse = function(elseFunction) {
      if (!this.length) {
        elseFunction();
      }
    };
    

    Used like this:

    $('#notAnElement').each(function () {
      alert("Wrong, it is an element")
    }).orElse(function() {
      alert("Yup, it's not an element")
    });
    

    Or, as it looks in CoffeeScript:

    $('#notAnElement').each ->
      alert "Wrong, it is an element"; return
    .orElse ->
      alert "Yup, it's not an element"
    

提交回复
热议问题