I spent over a half hour looking for the best solution to this. Personally, I blame the jQuery documentation. When reading over the jQuery
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 —
javascript, jquery
[…] here to read the rest: Detect an Empty Set in jQuery « Baron Knoxburry If you enjoyed this article please consider sharing […]
In your check, you can leave out the `==`.
if ($(‘.none’).length) {
…
}
would have the same outcome.
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.
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
…
” I hope this is helpful to someone in a similar situation! :D”
It is!
I love personal websites like this one for finding solutions to specific, uncommon issues like this one. I appreciate your time.