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

