[jquery] How can I detect if a selector returns null?

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

alert($('#notAnElement'));

you get [object Object], so the way I do it now is:

alert($('#notAnElement').get(0));

which will write "undefined", and so you can do a check for that. But it seems very bad. What other way is there?

This question is related to jquery jquery-selectors

The answer is


This is in the JQuery documentation:

http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/

  alert( $( "#notAnElement" ).length ? 'Not null' : 'Null' );

I like to do something like this:

$.fn.exists = function(){
    return this.length > 0 ? this : false;
}

So then you can do something like this:

var firstExistingElement = 
    $('#iDontExist').exists() ||      //<-returns false;
    $('#iExist').exists() ||          //<-gets assigned to the variable 
    $('#iExistAsWell').exists();      //<-never runs

firstExistingElement.doSomething();   //<-executes on #iExist

http://jsfiddle.net/vhbSG/


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"

The selector returns an array of jQuery objects. If no matching elements are found, it returns an empty array. You can check the .length of the collection returned by the selector or check whether the first array element is 'undefined'.

You can use any the following examples inside an IF statement and they all produce the same result. True, if the selector found a matching element, false otherwise.

$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined

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('...')

You may want to do this all the time by default. I've been struggling to wrap the jquery function or jquery.fn.init method to do this without error, but you can make a simple change to the jquery source to do this. Included are some surrounding lines you can search for. I recommend searching jquery source for The jQuery object is actually just the init constructor 'enhanced'

var
  version = "3.3.1",

  // Define a local copy of jQuery
  jQuery = function( selector, context ) {

    // The jQuery object is actually just the init constructor 'enhanced'
    // Need init if jQuery is called (just allow error to be thrown if not included)
    var result = new jQuery.fn.init( selector, context );
    if ( result.length === 0 ) {
      if (window.console && console.warn && context !== 'failsafe') {
        if (selector != null) {
          console.warn(
            new Error('$(\''+selector+'\') selected nothing. Do $(sel, "failsafe") to silence warning. Context:'+context)
          );
        }
      }
    }
    return result;
  },

  // Support: Android <=4.0 only
  // Make sure we trim BOM and NBSP
  rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

jQuery.fn = jQuery.prototype = {

Last but not least, you can get the uncompressed jquery source code here: http://code.jquery.com/


if ( $("#anid").length ) {
  alert("element(s) found")
} 
else {
  alert("nothing found")
}