What is the best way to detect if a jQuery-selector returns an empty object. If you do:
alert($(\'#notAnElement\'));
you get [object Object
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('...')
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.