How can I detect if a selector returns null?

前端 未结 8 1913
无人及你
无人及你 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条回答
  • I like to use presence, inspired from Ruby on Rails:

    $.fn.presence = function () {
        return this.length !== 0 && this;
    }
    

    Your example becomes:

    alert($('#notAnElement').presence() || "No object found");
    

    I find it superior to the proposed $.fn.exists because you can still use boolean operators or if, but the truthy result is more useful. Another example:

    $ul = $elem.find('ul').presence() || $('<ul class="foo">').appendTo($elem)
    $ul.append('...')
    
    0 讨论(0)
  • My favourite is to extend jQuery with this tiny convenience:

    $.fn.exists = function () {
        return this.length !== 0;
    }
    

    Used like:

    $("#notAnElement").exists();
    

    More explicit than using length.

    0 讨论(0)
提交回复
热议问题