Detect an Empty Set in jQuery April 24th, 2010 by b-knox

I spent over a half hour looking for the best solution to this.  Personally, I blame the jQuery documentation.  When reading over the jQuery core description it states, starting in version 1.4, that jQuery returns an empty set but offers no method to detect it.  Ultimately, I found that .length is the way to go but I wanted to expound on all three methods I discovered.

count with javascript

function jQueryCount(obj) {
var len = 0;
for (var k in obj)
len++;
return len;
}

This was the first type of solution I found.  Actually, I haven’t even tried it.  I knew right off the bat there has to be a built in jQuery function so I kept digging…

.size()

if ($('ul li:visible').size()==0) {
/* do stuff here if no visible li elements exist */
}

Yes! After scouring the API documentation for 20 minutes I finally stumbled upon what I was looking for — .size() It returns a count of elements inside a jQuery object. If there are no elements in the object it returns zero.

But what’s this?!?! The comments on the entry say it’s a stupid function that should be deprecated. The page suggests something better…

.length

if ($('ul li:visible').length==0) {
/* do stuff here if no visible li elements exist */
}

.length works in a different way to get a similar answer.  It seems to be “faster, and more consistent to JavaScript in general”.  I hope this is helpful to someone in a similar situation!  :D

Filed under — Uncategorized
Tags — ,

6 Responses to “Detect an Empty Set in jQuery”

  1. [...] here to read the rest: Detect an Empty Set in jQuery « Baron Knoxburry If you enjoyed this article please consider sharing [...]

  2. Alex Sexton says:

    In your check, you can leave out the `==`.

    if ($(‘.none’).length) {

    }

    would have the same outcome.

  3. b-knox says:

    Perhaps you meant

    if (!$(‘.none’).length) { }

    because .length returns the number of elements in a set and I only want the code in brackets to run if the set is empty. What you proposed would do the opposite. But if you hate the ‘==’ so much you can optimize out a few characters with the ! operand.

  4. b-knox says:

    geez… I also just found jQuery.isEmptyObject()!! So…

    if ($(‘.none’).isEmptyObject()) { }

    …should also work. :/

    .

    …and another one – this time without using a function…

    obj = $(‘.none’);
    if (!obj[0]) { }

    this looks for a first item in the object, if none found run the code, again untested :P

  5. Dani says:

    ” I hope this is helpful to someone in a similar situation! :D”

    It is!

  6. Andy says:

    I love personal websites like this one for finding solutions to specific, uncommon issues like this one. I appreciate your time.

Leave a Reply