Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get count of items jQuery.each()

I am parsing XML using jQuery. I want to get the count of all the sub nodes with the given tag name.

For example:

<People>
<person name="hello'></person>
<person name="hello'></person>
<person name="hello'></person>
<person name="hello'></person>
<person name="hello'></person>
</people>

I use the following jQuery Code:

$(xml).find("person").each(function(){});

Of course the above code works, but I just want to get the count, I do not want to loop. The reason is this: The above sample is too easy, my XML file and javascript code is a bit complex, so there is a lot of logic to figure out the xml file, and I don't want to spend code writing all that.

Many Thanks!

like image 725
harsimranb Avatar asked Feb 27 '12 22:02

harsimranb


People also ask

What is each() in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How do I count the number of elements in jQuery?

To count all HTML elements, we use length property. The length property is used to count number of the elements of the jQuery object.

How can I count the number of elements with same class?

To count the number of elements with a specific class: Use the querySelectorAll() method to get a collection of the matching elements. Access the length property on the collection. The length property will return the number of matching elements.

How to break each loop in jQuery?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.


2 Answers

If you want to get the count then use the length property:

$(xml).find("person").length;
  • API Reference: http://api.jquery.com/length/
like image 61
JaredPar Avatar answered Oct 05 '22 23:10

JaredPar


Or also try size():

$(xml).find("person").size();
like image 27
ZloyPotroh Avatar answered Oct 05 '22 23:10

ZloyPotroh