tags:

views:

1903

answers:

4

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?

+6  A: 
if( $("#anid").length ){
  alert("element(s) found")
}else{
  alert("nothing found")  
}
duckyflip
+4  A: 

The selector returns an array of jQuery objects. If no matching elements are found, it returns an empty array. You can check the length or size() of the array 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').size() > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined
Jose Basilio
+14  A: 

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.

Magnar
that's looking very sweet! Even though I marked this as answered, I'd still like to see more suggestions... (:
peirix
Much better answer than mine +1
Jose Basilio
Thanks for this! Can't get more convenient than that!
Sneakyness
such an elegant solution! Thanks!
Mike Grace