Get count of items jQuery.each()

18,824

Solution 1

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

$(xml).find("person").length;

Solution 2

Or also try size():

$(xml).find("person").size();
Share:
18,824
harsimranb
Author by

harsimranb

Updated on June 28, 2022

Comments

  • harsimranb
    harsimranb almost 2 years

    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!

  • Selvakumar Arumugam
    Selvakumar Arumugam about 12 years
    length is a property, not a function.
  • Rob Davis
    Rob Davis about 12 years
    length is an attribute, not a method. Drop those parens.
  • gen_Eric
    gen_Eric about 12 years
    Or .length, which may be faster.
  • charlietfl
    charlietfl about 12 years
    size() is being deprecated ...use length