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?
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.
I like to use
presence
, inspired from Ruby on Rails:Your example becomes:
I find it superior to the proposed
$.fn.exists
because you can still use boolean operators orif
, but the truthy result is more useful. Another example:This is in the JQuery documentation:
http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/
I like to do something like this:
So then you can do something like this:
http://jsfiddle.net/vhbSG/
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'
Last but not least, you can get the uncompressed jquery source code here: http://code.jquery.com/