94

Say I do

var s = $('#something');

and next I want to test if jQuery found #something, i.e. I want to test if s is empty.

I could use my trusty isempty() on it:

function isempty(o) {
    for ( var i in o )
        return false;
    return true;
}

Or since jQuery objects are arrays, I suppose I could test s.length.

But neither seem quite in the idiom of jQuery, not very jQueryesque. What do you suggest?

  • possible duplicate of http://stackoverflow.com/questions/299802/how-do-you-check-if-a-selector-exists-in-jquery – brettkelly Apr 15 '10 at 22:24
  • inkedmn, yes, similar question but I didn't see the `.size()` answer there, which I rather like. –  Apr 15 '10 at 23:37
  • possible duplicate of [Is there an "exists" function for jQuery?](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – Bergi Aug 02 '13 at 14:08
  • Possible duplicate of [How can I detect if a selector returns null?](http://stackoverflow.com/questions/920236/how-can-i-detect-if-a-selector-returns-null) – Malik Khalil Dec 19 '16 at 15:31

3 Answers3

109

Use the s.length property.

if(s.length == 0) {
    ...
}

[edit] size() deprecated in jquery 1.8 http://api.jquery.com/size/

Billiam
  • 2,349
  • 2
  • 19
  • 19
6
if($("#something").length > 0 ){
     // Element found
}
else{
    // No element found
}
Malik Khalil
  • 6,454
  • 2
  • 39
  • 33
0

An even more jQueryesque solution for me is:

jQuery.fn.isEmpty = function(fun){ if (this.length === 0) { fun(); } return this; };

This lets me write in typical fashion:

$("#sel").fadeOut(500,afterFade).isEmpty(insteadOfFade);
Don
  • 4,583
  • 1
  • 26
  • 33