Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if an object is a collection which can accept .each() in jQuery?

How to test if an object is a collection which can accept .each() in jQuery?

Thanks in advance!

like image 427
zs2020 Avatar asked Dec 22 '22 10:12

zs2020


2 Answers

Try length

if($('.my_class').length > 1)

http://jsfiddle.net/AlienWebguy/QhFDN/

like image 92
AlienWebguy Avatar answered Dec 24 '22 00:12

AlienWebguy


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){ ... });
}
like image 30
Guffa Avatar answered Dec 23 '22 23:12

Guffa