How can I detect if a selector returns null?

peirix picture peirix · May 28, 2009 · Viewed 204.8k times · Source

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?

Answer

Magnar picture Magnar · May 28, 2009

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.