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!
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.
To count all HTML elements, we use length property. The length property is used to count number of the elements of the jQuery object.
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.
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.
If you want to get the count then use the length
property:
$(xml).find("person").length;
Or also try size()
:
$(xml).find("person").size();
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