How to test if an object is a collection which can accept .each() in jQuery?
Thanks in advance!
Try length
if($('.my_class').length > 1)
http://jsfiddle.net/AlienWebguy/QhFDN/
If it's a jQuery object, you can always use the .each
method on it, even if there are no elements in it. If the jQuery object is empty it will just not enter the loop, so it's harmless to call .each
on an empty jQuery object:
obj.each(function(){ ... });
If you want to check if there are any items in a jQuery object, you can use the length
property.
if (obj.length > 0) {
...
}
If you want to check if an object is an array, so that you can use it in the $.each
method, you can use the $.isArray
method:
if ($.isArray(obj)) {
$.each(obj, function(index, value){ ... });
}
You can use $.each
to loop the properties of any object. You can use the isEmptyObject
to check if there are any properties:
if (!$.isEmptyObject(obj)) {
$.each(obj, function(key, value){ ... });
}
You can use the isPlainObject
method to determine if an object is created using new Object()
or an object literal { ... }
:
if ($.isPlainObject(obj)) {
$.each(obj, function(key, value){ ... });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With