Why does $('#id') return true if id doesn't exist? Why does $('#id') return true if id doesn't exist? jquery jquery

Why does $('#id') return true if id doesn't exist?


This behaviour was chosen because otherwise jQuery would regularly throw NullReference Exceptions

Almost all jQuery functions return a jQuery object as a wrapper around the Dom elements in question, so you can use dot notation.

$("#balloon").css({"color":"red"});

Now imagine $("#balloon") returned null. That means that $("#balloon").css({"color":"red"});would throw an error, rather than silently doing nothing as you would expect.

Hence, you just gotta use .length or .size().


This is just how jQuery works.

$("#something")

Object 0=div#something length=1 jquery=1.2.6

$("#nothing")

Object length=0 jquery=1.2.6


You can come close to doing what you want by accessing the length the element, and combine with the ternary operator:

console.log(!!$('#notfound').length);  // falseconsole.log(!!$('#exists').length);    // truevar element= $('#notfound').length ? $('#notfound') : $('#exists');console.log(element.attr('id'));  // outputs 'exists'

As to the heart of the question:

Wouldnt it be more logical if the ID selector returned null if not found?

No, not for the JQuery way of doing things - namely, to support chaining of JQuery statements:

    $('#notfound').hide("slow", function(){      jQuery(this)        .addClass("done")        .find("span")          .addClass("done")        .end()        .show("slow", function(){          jQuery(this).removeClass("done");        });    });

Even though notfound doesn't exist this code will run without stopping script execution. If the initial selector returns null, you'll have to add in an if/then block to check for the null. If the addClass, find, end and show methods return null, you'll have to add an if/then block to check the return status of each. Chaining is an excellent way to handle program flow in a dynamically typed language like Javascript.